可能重复:
How do I make a callable JS object with an arbitrary prototype?
假设我们有多个单独的函数,我们可以在它们自己的上下文中单独调用它们;但他们也继承了其他一些对象的原型。像这样:
//Here is the parent object:
var Human = function(){
this.isAlive = true;
};
Human.prototype.say = function(what){
alert(what + '!');
};
//These will inherit from it:
var ninja = function() {
alert("I'm a ninja!");
}
var samurai = function(){
alert("I'm a samurai!");
}
//Now, how can I make ninja and samurai behave like this:
ninja(); //I'm a ninja!
samurai(); //I'm a samurai!
ninja.say('Hello'); //Hello!
//And they should keep their inheritance. Like:
Human.prototype.die = function(){
this.isAlive = false;
}
ninja.die();
ninja.isAlive == false;
samurai.isAlive == true;
换句话说,有没有办法让两个对象继承另一个对象的原型,但仍然可以作为函数调用?
注意:我将在Adobe ExtendScript(又称为Crippled Javascript)中使用它,并且它不太了解现代的javascript。就像,Object.defineProperty不起作用。那么,有没有一种正常的标准方法呢?
答案 0 :(得分:3)
使用apsillers的链接问题,我能够使用一个调整:Human
的属性和方法被定义为对象:
尝试一下:http://jsfiddle.net/lbstr/JZP2S/
关键是HumanMaker
功能。在基本级别,它需要一个函数并将Human
原型添加到它。这允许您调用您的函数,从Human
获取所有属性并将其吃掉。这是:
function HumanMaker(f) {
var h = Human;
h.__proto__ = f.__proto__;
f.__proto__ = h;
return f;
}
您可以这样调用它:
var ninja = HumanMaker(function() {
alert("I'm a ninja!");
});
以下是整个事情:
var Human = {
isAlive: true,
say: function(what){
alert(what + '!');
},
die: function(){
this.isAlive = false;
}
};
function HumanMaker(f) {
var h = Human;
h.__proto__ = f.__proto__;
f.__proto__ = h;
return f;
}
//These will inherit from it:
var ninja = HumanMaker(function() {
alert("I'm a ninja!");
});
var samurai = HumanMaker(function(){
alert("I'm a samurai!");
});
//Now, how can I make ninja and samurai behave like this:
ninja(); //I'm a ninja!
samurai(); //I'm a samurai!
ninja.say('Hello'); //Hello!
ninja.die();
ninja.isAlive == false;
samurai.isAlive == true;
答案 1 :(得分:0)
我总是发现功能继承模式更容易理解:
var human = function(){
var me = {};
var _isAlive = true;
Object.defineProperty(me, "isAlive", {
get: function() { return _isAlive}
});
me.say=function(what){
if(_isAlive)
alert(what+'!');
else
throw new Error('I am dead!');
}
me.die=function(){
_isAlive = false;
}
return me;
};
var person = function(){
var me = human();
return me;
};
var ninja = function(){
var me = human();
me.say = function(what){
if(me.isAlive)
alert(what+', I am a ninja!');
else
throw new Error('I am dead!');
};
return me;
};
var myPerson = person();
myPerson.say('hi');
var myNinja = ninja();
myNinja.say('hello');
我在这里留下了一个演示:http://jsfiddle.net/vtortola/nbpPt/
干杯。