constA={setName:function(name){this.name = name
},getName:function(){return'my name is '+this.name;},}// 使 B 委托到 A, B的[[protoType]]会指向A对象constB= Object.create(A);//Object.create作用:以一个现有对象为原型创建一个新对象B.greeting=function(){
console.log('hello, '+this.getName());}//使 b1 委托到 B, b1的[[protoType]]会指向B对象const b1 = Object.create(B);// 通过原型链访问A对象上方法
b1.setName('b1');//使 b2 委托到 B, b2的[[protoType]]会指向B对象const b2 = Object.create(B);
b2.setName('b2');// 通过原型链访问B对象上方法
b1.greeting()// hello, my name is b1
b2.greeting()// hello, my name is b2
行为委托意味着:在访问某个对象上不存在的属性或方法时,让这个对象为属性或方法引用提供一个委托。可以多级委托,但是不能相互委托,不能在两个或多个对象间相互地委托(双向地)对方来创建一个 循环 。比如使 B 链接到 A,然后试着让 A 链接到 B。
functionA(name){this.name = name
}A.prototype.getName=function(){return'my name is '+this.name
}functionB(name){// this的显式绑定:this指向A,并调用A函数初始化nameA.call(this,name)}// B继承A// 将A.prototype对象作为B的原型对象,B.prototype继承了A.prototype的属性和方法B.prototype = Object.create(A.prototype);B.prototype.greeting=function(){
console.log('hello, '+this.getName());}// 调用 B函数,创建一个新对象b1,并将this指向b1const b1 =newB('b1');const b2 =newB('b2');
b1.greeting();// hello, my name is b1
b2.greeting();// hello, my name is b2
在 JS 中,构造器 仅仅是一个函数,它们偶然地与前置的 new 操作符一起调用。它们不依附于类,它们也不初始化一个类。它们甚至不是一种特殊的函数类型。它们本质上只是一般的函数,在被使用 new 来调用时改变做了附加的行为。(创建一个新对象,并将this指向这个新对象)