我有一个fiddle可以帮助我理解JavaScript原型和继承。这些评论说明了这个故事。
//From Douglas Crockford's "Javascript: the good parts": a helper to hide the "ugliness" of setting up a prototype
Function.prototype.method = function(name,func) {
this.prototype[name] = func;
return this;
}
function SomeFunc(value) {
this.setValue(value);
}
//Inherit the function (to me this conceptually the same as adding a member to a class)
SomeFunc.method('setValue', function (value) {
this.value = value;
return this;
});
try
{
SomeFunc(1);
}
catch(e)
{
alert(e);
}为什么我会得到一个异常?我的注释是否正确,因为JavaScript调用继承就是给经典程序员简单地向类添加一个新成员?增强和继承之间的区别是什么?
发布于 2011-10-19 03:11:41
相反,尝试:
new SomeFunc(1);因为这是原型工作时的情况。
https://stackoverflow.com/questions/7812085
复制相似问题