简体   繁体   English

什么时候对象的原型链上的方法可以调用?

[英]when is a method on an object's prototype chain callable?

Consider this code... 考虑这段代码......

var org = {};

org.Organization = function() {

    var app = null;
    function setupApplication() {};

    return {
        init : function() {
            console.log("init");
        }
    }
};

org.Organization.prototype = {
    status : function() {
        console.log("status");
    }
};

var myOrg = new org.Organization();
myOrg.init();      // outputs "init"
myOrg.status();    // TypeError: Object #<Object> has no method 'status'

... the status() method does not exist and I can't call it :( However, if I were to remove the return { ... } like so... ... status()方法不存在,我无法调用它:(但是,如果我要删除return { ... }这样......

var org = {};

org.Organization = function() {

    var app = null;
    function setupApplication() {};
};

org.Organization.prototype = {
    status : function() {
        console.log("status");
    }
};

var myOrg = new org.Organization();
myOrg.init();      // TypeError: Object #<Object> has no method 'init
myOrg.status();    // outputs "status"

... then the status() method does exist and I can call it with no problems. ...然后status()方法确实存在,我可以毫无问题地调用它。 Why is this happening? 为什么会这样? Why can a method on the prototype chain be called only when original object has no return { ... } ? 为什么只有在原始对象没有return { ... }时才能调用原型链上的方法? Does the return { ... } overwrite or take precedence over the methods on the prototype chain? return { ... }是否覆盖原型链上的方法或优先于原型链上的方法?

When you use return obj in a function constructor, it will return that actual object, not the object that has been constructed internally. 在函数构造函数中使用return obj时,它将返回该实际对象,而不是内部构造的对象。 If you want it to work correctly, simply define init within the constructor like so: 如果你想让它正常工作,只需在构造函数中定义init,如下所示:

this.init = function() { };

To give a few more details: when you call new Func , what happens internally is that a new object (with the prototype set to the function's prototype) is created and the constructor function is called with the object set as this . 为了给出更多细节:当你调用new Func ,内部发生的是创建一个新对象(原型设置为函数的原型),并在对象设置为this调用构造函数。 At the end of the constructor, the same object is returned, unless you return another object manually, in which case that object will be returned, which will obviously not have the same prototoype. 在构造函数的末尾,返回相同的对象,除非您手动返回另一个对象,在这种情况下将返回该对象,这显然不会具有相同的原型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM