对象的原型
function A(){
this.do=function() {return 'foo'}
}
//原型的两种写法01
// A.prototype={
// constructor:A,
// do:function() {return 'bar'}
// }
//原型的两种写法02
A.prototype=function() {
this.do=function() {return 'bar'}
}
var x=new A().do()
console.log(x)
function Student(name,age,sex){
this.name=name
this.age=age
this.sex=sex
// this.sayHi=function(){
// console.log("hello"+this.name)
// }
// 在构造函数里写方法的缺点:
// 之后会在每个创建的实例都开辟一个内存空间存放这个sayHi的方法
//这里我们使用这个构造函数的原型创建一个sayHi方法如下:
}
Student.prototype.sayHi=function(){
console.log("hello"+this.name)
}
//换种方式写原型对象
Student.prototype={
constructor:Student,//指回构造函数
sayHi:function(){
console.log("hello"+this.name)
},
eat:function(){
console.log(this.name+"eat")
}
}
var s1=new Student("Eric",22,"男")
console.log(s1.__proto__===Student.prototype)
console.dir(s1.__proto__)
console.dir(Student.prototype)
// 需要注意的是在构造函数的原型中创建了一个方法之后,
// 也会相应的的在实例会的那个s1对象中有一个__proto__的属性存放着指向Student.prototype
//
/*
*下图清晰的介绍了三角关系和原型链
*/


浙公网安备 33010602011771号