关于 js 中使用 call 实现继承:call/apply 网上有很多说明,但基本上都没有阐释它的实际运行机制,总是说将 A 的方法全部给了 B, 但是原因是什么,我还没看到有那篇文章说明过。说明之前首先必须要说先说明几个概念。
- function ClassA(sColor) {
- this.color = sColor;
- this.sayColor = function () {
- alert(this.color);
- };
- }
- function ClassB(sColor, sName) {
- ClassA.call(this, sColor);
- this.name = sName;
- this.sayName = function () {
- alert(this.name);
- };
- }
- var objA = new ClassA("blue");
- var objB = new ClassB("red", "John");
- objA.sayColor();
- objB.sayColor();
- objB.sayName();
ClassA.call(this, sColor)可以这么理解,就是把 ClassA 中的 this,换成 (this,sColor) 中的 this, 也即是将 ClassA 中 this 替换为 ClassB 的 this,所以实例化 ClassB 时其中的 this, 不仅仅在 ClassA 中被赋值了,也在 ClassB 中被赋值了,即 this.color=sColor;this.Saycolor=function(){}。 所以 objB 可以调用 sayColor(), 因为 objB==this, 这个 ClassA 的 this 又在 ClassB 中被赋值过。
在 ClassA(),ClassB() 中我没有写 return 语句,或者你写 "return 2" 返回基本类型时,是默认返回 this 的。然后 this 也是一个很复杂的玩意,在这里是构造函数中的 this, 这种情况下,this 一开始是一个空对象,原型指向 ClassA() 的 prototype 属性, 实例化时 this.Saycolor=function(){//do sth} 给 this 赋值。 所以 objA.sayColor() 可以使用。
来源: http://www.2cto.com/kf/201704/628807.html