[英]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.