使用 new 关键字的函数原型继承

function prototype inheritance with new keyword

我确保我正确理解了 JavaScript 的 newprototype 关键字,但是我放在一起的一些简单代码并没有像我预期的那样运行。

var ClassA = function() {
    return {
        shout: function() {
             alert("I can shout");
        }
    };
};
ClassA.prototype.shoutLouder = function() {
     alert("I CAN SHOUT");
};

var instance = new ClassA();
instance.shout();

// why not available?
instance.shoutLouder();

当实例变量尝试调用 shoutLouder 时失败并显示 "Uncaught TypeError: instance.shoutLouder is not a function".

但是,在mozilla docs中,它说当使用new创建对象时:

A new object is created, inheriting from Foo.prototype.

我的理解哪里错了?

Here is a jsbin 上面的代码片段。

ClassA returns 一个新的、不同的对象

 return {
        shout: function() {
             alert("I can shout");
        }
    };

尝试

var ClassA = function() {
    this.shout = function() {
             alert("I can shout");            
    };
};
ClassA.prototype.shoutLouder = function() {
     alert("I CAN SHOUT");
};

var instance = new ClassA();

instance.shout();

// why not available?
instance.shoutLouder();

您将无法访问函数的 (Class') 原型对象,因为您return正在从函数中创建一个新对象:

var ClassA = function() {
    return {
        shout: function() {
             alert("I can shout");
        }
    };
};

而你应该这样做:

var ClassA = function() {
    this.shout = function() {
        alert("I can shout");
    };
};

这仍然会让您访问原型对象(因此委托链仍然有效),因为新关键字将 return 'this' 来自 Class.