【发布时间】:2014-02-09 10:22:44
【问题描述】:
我正在尝试理解 Javascript 中的 原型继承,但未能适用于以下情况。任何帮助将不胜感激。
我正在定义一个构造函数如下:
var base = function() {
var priv = "private"; // Private
var publ = "public"; // Public through a getter/setter (below)
// The object to return
var f = {};
f.publ = function (new_val) {
if (!arguments.length) {
return publ;
}
publ = new_val;
return f;
};
return f;
};
使用这个构造函数,我可以通过调用base(); 创建对象。这些对象有一个公共方法(publ)。
现在,按照相同的结构,我想要一个新的构造函数,它创建的对象继承自上面定义的“基本构造函数”创建的对象:
var myclass = function () {
// Other parameters defined here
var f = function () {
// publ is inherited
console.log(f.publ());
};
// Trying to set the prototype of f to the object created by "base()"
f.prototype = base();
// Other methods defined here
return f;
};
对于f.prototype = base();,我想让f继承base()返回的对象中定义的所有方法,但是尝试调用f.publ会报错,因为f没有方法publ
欢迎任何帮助了解正在发生的事情
M;
【问题讨论】:
-
javascript 中的原型继承需要
new运算符或Object.create。您在这里都没有使用。 -
这看起来不像构造函数。您可以将构造函数与
new一起使用。它看起来更像是一个模块模式。 -
如几个 cmets 中所述,使用 Object.create 设置继承的原型部分并在 Child 中执行 Parent.call(this,args)(这将负责从 Parent 继承实例成员)。更多信息在这里stackoverflow.com/a/16063711/1641941
标签: javascript prototypal-inheritance