簡體   English   中英

使用Function.apply()使用原型構造對象

[英]Construct an object with a prototype using Function.apply()

我對JS的原型繼承有個困惑。 我想做的是:

  1. 定義一個名為mod的對象

     var mod = function() { function sayGoodbye() { alert("Goodbye!"); } function saySomethingElse(message) { alert(message); } return { sayGoodbye: sayGoodbye, saySomethingElse: saySomethingElse }; }; 
  2. 定義一個稱為proto的原型對象

     var proto = { sayHello: function() { alert("Hello!"); } }; 
  3. mod的原型設置為proto

     mod.prototype = proto; 
  4. 調用一個函數,該函數使用proto原型構造mod的新實例

     function construct(constructor, args) { function constructorWrapper() { return constructor.apply(this, args) } constructorWrapper.prototype = constructor.prototype; return new constructorWrapper(); } var foo = construct(mod, ["Other Message 1"]); var bar = construct(mod, ["Other Message 2"]); console.dir(foo); console.dir(bar); 

構造函數使用apply函數正確創建了mod的新實例,但是它的原型不是proto 我缺少的是防止國防部正在建造之中,它的原型?

這是上面代碼的小提琴

謝謝堆!

.prototype分配對您.prototype的原因是,像這樣設置原型鏈僅在對構造函數使用new運算符時才有效。

您創建了一個工廠函數,該函數返回一個新創建的對象。 擺脫mod中的return ,並使用this來附加您的方法,並在創建mod實例時使用new運算符使.prototype分配起作用。

這可能令人困惑,所以我更新了您的小提琴: https : //jsfiddle.net/6fdo649y/1/

有幾種方法可以實現您要完成的任務,但是此示例說明了為什么您看不到.prototype工作。

//Constructor function using this
function Mod(arg1) {
    this.sayGoodbye = function sayGoodbye() {
        alert("Goodbye!");
    }

    this.saySomethingElse = function saySomethingElse(message) {
        alert(message);
    }

    this.arg1 = arg1;
};

var proto = {
    sayHello: function() {
        alert("Hello!");
    }
};

Mod.prototype = proto;

function construct(constructor, args) {

    function constructorWrapper() {
        constructor.apply(this, args)
    }

    constructorWrapper.prototype = constructor.prototype;

    return new constructorWrapper();
}

var foo = construct(Mod, ["Other Message 1"]);
var bar = construct(Mod, ["Other Message 2"]);

console.dir(foo === bar);
console.dir(foo);
console.dir(bar);

編輯:通過傳遞與應用的參數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM