gpt4 book ai didi

javascript - JS模板方法模式中 `this`的含义

转载 作者:行者123 更新时间:2023-11-28 02:28:07 25 4
gpt4 key购买 nike

为什么标记的行找不到protectedACMember

var Module = (function (ns) {

function AbstractClass() {
this.protectedACMember = "abstract";

this.abstractPublicACMethod = function (input) {
this.methodToImplement();
}
}

ConcreteClass.prototype = new AbstractClass();
function ConcreteClass(){
var privateCCMember = "private CC";

var privateCCMethod = function(){
alert(this.protectedACMember); // cant find protectedACMember
}

this.methodToImplement = function(){
privateCCMethod();
console.log('Implemented method ');
}

}

ns.ConcreteClass = ConcreteClass;

return ns;

})(Module || {});

//somewhere later
var cc = new Module.ConcreteClass();
cc.abstractPublicACMethod();

是否有任何好的模式来模拟私有(private)、 protected 和公共(public)成员?静态/非静态也是如此?

最佳答案

您应该像这样更改这部分代码:

    var self = this;
var privateCCMethod = function(){
alert(self.protectedACMember); // this -> self
}

这样你就可以在闭包中获得引用。

原因是,“this”是一个保留字,它的值是由解释器设置的。您的 privateCCMethod 是一个匿名函数,而不是对象属性,因此如果您仅通过 privateCCMethod() 语法调用它,则 this 将为 null。如果您希望将“this”绑定(bind)到特定的内容,您可以随时使用 .call 语法,如下所示:

privateCCMethod.call(this)

关于javascript - JS模板方法模式中 `this`的含义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14584449/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com