使 JavaScript 函数继承原型



可能的重复项:
如何使用任意原型制作可调用的 JS 对象?

假设我们有多个单独的函数,我们可以在它们自己的上下文中单独调用它们;但它们也继承了其他一些对象的原型。喜欢这个:

//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在其中不起作用。那么,有没有一种正常的、标准的方法呢?

使用 apsilers 的链接问题,我能够通过一个调整来让它工作: 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;​
我一直

发现函数继承模式更容易理解:

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/

干杯。

最新更新