使用Function.apply()

时间:2016-02-25 04:53:29

标签: javascript inheritance constructor prototype instance

我有点陷入困境让我的头脑绕过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);
    
  5. 构造函数使用 apply 函数正确创建 mod 的新实例,但它的原型不是即可。我错过了什么阻止 mod 使用 proto 构建它作为原型?

    以下是包含上述代码的fiddle

    谢谢堆!

1 个答案:

答案 0 :(得分:1)

.prototype赋值不适合你的原因是因为只有在构造函数上使用new运算符时才能设置这样的原型链。

您创建了一个返回新创建对象的工厂函数。摆脱return中的mod并使用this附加您的方法,并在创建new的实例时使用mod运算符将.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);

编辑:通过apply传递了args。

相关问题