Parent = (function() {
var parent = function(name) {
this.name = name;
};
parent.prototype.dostuff = function() {
console.log(this.name);
};
parent.prototype.more = function() {
console.log("this should be available on both ... " + this.name);
};
return parent;
}());
Child = (function() {
var child = function(name) {
Parent.call(this, name);
this.prototype = Object.create(Parent.prototype);
};
child.prototype.dostuff = function() {
console.log("the child class ... " + this.name);
};
child.prototype.special = function() {
console.log("only the child has this method");
};
return child;
}());
在上面我的父对象有一个名为“more”的方法,但是当我像这样新建子对象时..我无法调用more方法,除非我手动原型(prototype)化它。上面我缺少什么可以让我免费获得原型(prototype)方法?
var first = new Parent("father");
var last = new Child("son");
使用 jsfiddle 进行更新
最佳答案
您在实例上设置原型(prototype),您应该在函数本身上设置它。
当使用new
创建对象时,构造函数中的this
指的是对象本身。但原型(prototype)是用作构造函数的函数的属性,而不是实例的属性。
所以你想要这样的东西:
Child = (function() {
var child = function(name) {
Parent.call(this, name);
};
child.prototype = Object.create(Parent.prototype);
child.prototype.dostuff = function() {
console.log("the child class ... " + this.name);
};
child.prototype.special = function() {
console.log("only the child has this method");
};
return child;
}());
Child的原型(prototype)被设置为一个新对象,其原型(prototype)上有parent的原型(prototype),允许它继承一切。
关于javascript - 为什么子对象没有使用模块模式的父方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16329160/