(原谅我的小关于原型遗传的括号。你可以跳过这个并看到下面的答案。
为了让对象扩展另一个对象,child
的原型必须是其实例parent
。你可以在网上找到很多关于这方面的优秀资源,但不幸的是,也有很多不好的资源,所以我建议你在本文中采取一个高峰:http://javascript.crockford.com/prototypal.html。
A 新对象通过new
实例化关键字:new f()
返回它的原型对象的副本:f.prototype
。承认这一点,你就会意识到,为了扩展对象x
,你当前对象的原型必须是一个新的x实例:
function Person(){};
Person.prototype.speak = function(){
alert("I'm a person");
}
function StackoverflowUser(){};
StackoverflowUser.prototype = new Person();
// now StackOverflowUser is a Person too
)
你实际上并不需要为underscore.js :
var InternalError = function(msg,args){
return this.initialize(msg||{},args);
}
// inherit from the Error object
InternalError.prototype = new Error();
// overwrite the constructor prop too
InternalError.constructor = InternalError;
InternalError.prototype.initialize = function(msg,args){
this.message = msg;
this.name = 'InternalError';
}
var err = new InternalError("I'm an internal error!");
alert(err instanceof Error); // true
throw err;
,如果你真的想用underscore.js:
var InternalError = function(msg,args){
return this.initialize(msg||{},args);
}
_.extend(InternalError.prototype,new Error(),{
initialize : function(msg,args){
this.message = msg;
this.name = 'InternalError';
},
constructor : InternalError
});
+1,并且答案很好,但我会指定InternalError.prototype.constructor = InternalError,而不是将'constructor'设置为实例属性。 –
thx,我已经更新了示例以在原型中包含构造函数。 –
@ gion_13似乎你仍然在使用'InternalError.constructor = InternalError;'而不是'InternalError.prototype.constructor = InternalError' – Leonardo