原型揭示模式和'这'嵌套函数或返回对象中

Prototype Revealing Pattern and use of 'this' in Nested Functions or return object

本文关键字:函数 返回 对象 嵌套 原型 模式      更新时间:2023-09-26

我一直在使用原型揭示模式,下面是一个简单的例子。

如果我返回未注释的对象以公开原型函数中的公共函数,效果会很好,如jsFiddle 所示

另一方面,如果我使用另一个嵌套对象(注释掉的对象(在不同的层次结构中组织返回的公共函数,则函数仍然可以被调用,但instanceVar在"this"中未定义

我理解为什么(我想(,但我不确定如何传递正确的"this"实例,或者使用这种模式是否可能,我想知道是否有人知道如何实现这一点?

我已经试过了。用很多方法打电话(这个(,但仍然得不到任何乐趣。

WhoSays = function (sentence) {
    this.instanceVar = sentence;
};
WhoSays.prototype = (function () {
    var jimSays = function () {
        return 'jim says ' + this.instanceVar;
    };
    var bobSays = function () {
        return 'bob says ' + this.instanceVar;
    };
    /*return {
        says : {
            jim : jimSays,
            bob : bobSays
        }
    };*/
    return {
        jim: jimSays,
        bob: bobSays
    };
}());

更新:

我不想修改调用,调用方不需要知道如何使用显而易见的模式。

我确信这可能不是一种明智的方法,命名空间层次结构可能是一种更好的方法,但我仍然感兴趣的是,如果不使用调用从调用方的角度绑定"this",例如who.say.jim.apply(who(

如果你真的想让它像你尝试的那样工作,那么就这样使用它:

WhoSays = function (sentence) {
    this.instanceVar = sentence;
};
WhoSays.prototype = function () {
    var jimSays = function () {
        return 'jim says ' + this.instanceVar;
    };
    var bobSays = function () {
        return 'bob says ' + this.instanceVar;
    };
    return {
        says : {
            jim : jimSays,
            bob : bobSays
        }
    };
    /*
    return {
        jim: jimSays,
        bob: bobSays
    };*/
}();
var who = new WhoSays("works!");
console.log(who.says.jim.apply(who)); // logs "jim says works!"

这告诉你为什么它现在工作!

当您调用new WhoSays().says.jim()时,thisnew WhoSays().says,而不是您想要的new WhoSays()

你可以试试:

WhoSays.prototype = (function () {
    return {
        says: function() {
            var self = this;
            return {
                jim : function() {
                    return 'jim says ' + self.instanceVar;
                },
                bob : function() {
                    return 'jim says ' + self.instanceVar;
                },
            }
        };
    };
}());

然后调用CCD_ 5。

或者使用Object.defineProperty来定义getter says以用于符号偏好。

我个人的偏好是使用更传统的方式来获得你想要的东西。

您可以尝试以下代码:

var WhoSays = function (sentence) {
  this.instanceVar = sentence;
  this.says=new Says(this);
};
var Says = function(whoRef) {
  this.whoRef=whoRef;
};
Says.prototype.jim = function () {
  return 'jim says ' + this.whoRef.instanceVar;
};
Says.prototype.bob = function () {
  return 'bob says ' + this.whoRef.instanceVar;
};
var b = new WhoSays("b");
console.log(b.says.jim());
var c = new WhoSays("c");
console.log(c.says.jim());
console.log(b.says.jim());

关于原型、继承、重写的更多信息https://stackoverflow.com/a/16063711/1641941

了解this可以是什么:https://stackoverflow.com/a/19068438/1641941