我有一个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调用继承是古典程序员简单地向类中添加新成员?增强和继承有什么区别?
一开始的情况下,看看[使用对象](https://developer.mozilla.org/en/JavaScript/Guide/Working_with_Objects)和[继承和原型链](https://developer.mozilla.org/zh/JavaScript/Guide/Inheritance_constructor_prototype)。 –
你在'SomeFunc(1)'之前忘了''''' – Kru
@Kru - 修正了错误。为什么需要新的? –