gpt4 book ai didi

javascript - 模块化模式中的私有(private)实例变量

转载 作者:行者123 更新时间:2023-12-02 18:10:48 24 4
gpt4 key购买 nike

var foo = (function(){

var _blah;

function doStuff(){
//how to make _blah instance specific
//and access it here?
}

function bar(blah){
_blah = blah;
doStuff();
//this.blah = blah?
}

bar.prototype.getBlah = function(){ return _blah; };

return bar;

})();

var foos = [];

$.each([1,2,3], function(i, v){
var f = new foo(v);
foos.push(f);
});

//all instances of foo
//gets _blah set to 3
console.log(foos[1].getBlah());

我对上述模块有两个问题:

  • 如何设置每个实例特定的属性?现在您可以看到 _blah 被覆盖,这是非常明显的。但我需要一些语法方面的帮助。我的猜测是我需要像注释一样在构造函数中设置它。这是正确的做法吗?
  • 如何通过其他方法访问该属性?据我所知,this指的是doStuff()中的window

http://jsfiddle.net/ncg2M/1/

最佳答案

How do I set a property that is specific for each instance? Right now you can see that _blah gets overwritten, which is pretty obvious. But I need some help with the syntax. My guess is that I need to set it in the constructor like the comment. Is that the right way to do it?

是的。这是正确的方法,使用 this.blah =//value,当然,这使得变量 blah 可以不受任何限制地公开访问。

How do I access the property in another method? As far as I know, this refers to window in doStuff().

doStuff() 方法没有多大意义,因为当您在模块内定义类似的函数时,它通常是由其他实例方法使用的实用函数。

关于javascript - 模块化模式中的私有(private)实例变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19728478/

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