[英]Why doesn't this simple Object.create example work?
下面的代碼說對象沒有方法呵呵
var A = function () {
this.hehe = function () { };
};
var B = function () {};
B.prototype = Object.create(A.prototype, {
constructor: {
value: B,
enumerable: false,
writable: true,
configurable: true
}
});
var _b = new B();
_b.hehe();
如果您希望B能夠訪問該功能,則需要在A的原型中定義它。
A.protototype.hehe = function(){
//do something
};
b中也缺少對父母構造函數的調用。
有了這個,他的每個實例都得到了它自己的功能,因此不在原型中。
同樣更好地實現原型不合理如下 - 這是我所知道的意見問題。
function __extends(child,parent){ //Global function for inheriting from objects
function Temp(){this.constructor = child;} //Create a temporary ctor
Temp.prototype = parent.prototype;
child.prototype = new Temp(); //Set the child to an object with the child's ctor with the parents prototype
}
var B = (function(_parent){
__extends(B,A);
function B(){
_parent.call(this);
}
})(A);
您應該傳遞A的實例作為原型,而不是A的原型。
即你應該調用你的創建調用應該看起來像Object.create(new A(), ...
hehe()
不是A.prototype
的成員; 它是在其構造函數中分配的每個A
實例的屬性。
由於你從不調用A
構造函數, _b
沒有它。
您需要在派生構造函數中調用基礎構造函數:
A.call(this);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.