不知何故,JS继承并没有在我脑海中浮现。我现在尝试了很多东西,由于某种原因,我无法向继承的对象添加方法。
请参阅我的定义B.setC
的尝试,然后以某种方式无法使用。任何提示?
欢呼声 汤姆
A = function( value){
this.aValue = value;
}
B = function(value){
A.call(this, value);
this.bValue=value+value;
}
B.prototype = Object.create(A.prototype);//subclass extends superclass
B.setC = function(value){
this.c = value+value+value;
console.log("execution");
}
B.prototype.setD = function(value){
this.D = value+value+value+value;
console.log("execution");
}
x = new B("ConstructorParam");
x.setC("methodParam");// gives that setC is not a function
x.setD("methodParam");// works but I added setD to A not B
答案 0 :(得分:3)
混淆似乎来自这种误解;引用你的评论:
实际上这不是拼写错误。我想将setC添加到B而不是A,如果我的理解是正确的,并且我在Chrome中看到的调试是,如果我使用B.prototype.setB然后我将setB添加到B又名A的原型而不是B。或者我错过了吗?
这个评论中也显示了这个问题:
x.setD("methodParam");// works but I added setD to A not B
B.prototype
不是A
。 B.prototype
是一个以A.prototype
为原型的对象。您已将setD
正确添加到B.prototype
;它不以任何方式添加到A
或A.prototype
。
如果您希望按照展示方式使用setC
和setD
,则可以将它们放在B.prototype
上(因此可以在B
的实例上访问它们)在A.prototype
上(因此可以在A
或B
的实例上访问它们。
如果我们将B.setC =
更改为B.prototype.setC =
,请将d
小写设置为匹配c
,添加一些缺少的var
,并在创建时使用较短的值并调用方法,我们得到这个:
var A = function( value){
this.aValue = value;
};
var B = function(value){
A.call(this, value);
this.bValue = value + value;
};
B.prototype = Object.create(A.prototype);//subclass extends superclass
B.setC = function(value){
this.c = value + value + value;
console.log("execution");
};
B.prototype.setD = function(value){
this.d = value + value + value + value;
console.log("execution");
};
var x = new B("b");
x.setC("c");
x.setD("d");
在最后一行代码之后,这就是我们在内存中的内容(减去一堆不必要的细节):
+−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+ | | \ +−−−−−−−−−−−−−−−+ | A−−−−−−−−−>| function | | +−−−−−−−−−−−−−−−+ +−−−−−−−−−−−−−+ | | prototype |−−−−−−−−−−−−−−−−−−−−−−−−−−−−>| object | | +−−−−−−−−−−−−−−−+ / +−−−−−−−−−−−−−+ | | | constructor |−+ | +−−−−−−−−−−−−−+ +−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+ | | | | \ +−−−−−−−−−−−−−−−+ | | B−−−−−−−−−>| function | | | +−−−−−−−−−−−−−−−+ +−−−−−−−−−−−−−−−−−−+ | | | prototype |−−−>| object | | | +−−−−−−−−−−−−−−−+ / +−−−−−−−−−−−−−−−−−−+ | | | | constructor |−+ | | | setC: (function) | | | | setD: (function) | | | | [[Prototype]] |−−−+ +−−−−−−−−−−−−−−−+ | +−−−−−−−−−−−−−−−−−−+ x−−−−−−−−−>| object | | +−−−−−−−−−−−−−−−+ | | aValue: "a" | | | bValue: "aa" | | | c: "ccc" | | | d: "dddd" | | | [[Prototype]] |−−+ +−−−−−−−−−−−−−−−+上面的
[[Prototype]]
是规范用于包含对其原型对象的引用的对象的“内部槽”的名称。相比之下,prototype
,函数上的属性(例如,A.prototype
),只是函数的正常属性,指向new
将用作[[Prototype]]
的对象如果将该函数与new
一起使用,则会创建新对象。
为了完整起见,这是在ES2015 +:
class A {
constructor(value) {
this.aValue = value;
}
}
class B extends A {
constructor(value) {
super(value);
this.bValue = value + value;
}
setC(value) {
this.c = value + value + value;
console.log("execution");
}
setD(value) {
this.d = value + value + value + value;
console.log("execution");
}
}
let x = new B("b");
x.setC("c");
x.setD("d");