1.我们需要牢记两点:①__proto__和constructor属性是对象所独有的;② prototype属性是函数所独有的,因为函数也是一种对象,所以函数也拥有__proto__和constructor属性。
2.__proto__属性的作用就是当访问一个对象的属性时,如果该对象内部不存在这个属性,那么就会去它的__proto__属性所指向的那个对象(父对象)里找,一直找,直到__proto__属性的终点null,再往上找就相当于在null上取值,会报错。通过__proto__属性将对象连接起来的这条链路即我们所谓的原型链。
3.prototype属性的作用就是让该函数所实例化的对象们都可以找到公用的属性和方法,即f1.proto === Foo.prototype。
4.constructor属性的含义就是指向该对象的构造函数,所有函数(此时看成对象了)最终的构造函数都指向Function。
function Foo(name,age){
this.name=name;
this.age=age;
}
Object.prototype.toString=function(){
//this是什么要看执行的时候谁调用了这个函数。
console.log("I'm "+this.name+" And I'm "+this.age);
}
var fn=new Foo('小明',19);
fn.toString(); //I'm 小明 And I'm 19
console.log(fn.toString===Foo.prototype.__proto__.toString); //true
console.log(fn.__proto__ ===Foo.prototype)//true
console.log(Foo.prototype.__proto__===Object.prototype)//true
console.log(Object.prototype.__proto__===null)//true
//原型链的两种操作方式
//一:
function Foo(name,age){
this.name=name;
this.age=age;
}
//继承在添加一个构造函数
function Too(){}
var fn=new Foo('小明',19);
//原型添加方法
Foo.prototype.eat=function (){
return 'tttttt'
}
//将Foo生成的实例赋予Too构造函数原型
Too.prototype= new Foo('小红',22)
let p = fn.eat()
let kk = new Too()
console.log(Too.prototype)
console.log(kk.eat())
console.log(fn)
console.log(fn.eat)
console.log(p)
//二:
class gg {
constructor(x, y) {
this.x = x;
this.y = y;
}
eat(){
return 'sssssssss'
}
}
let gk = new gg(1,'tt')
let ck = new gg(2,'ss')
gk.x= 5
let o = gk.eat()
let b = ck.eat()
console.log(gk.x)
console.log(ck.x)
console.log(gk.eat)
console.log(o)
console.log(b)