使用闭包创建的私有函数如何访问构造函数中定义的变量
How private function created with closure can access variable defined in constructor?
我有以下代码:
var TagCloud = (function() {
var createTagsArray = function() {
j$("#" + this.cloudId + " a").each(function(index) {
//bla bla
});
}
function TagCloud(cloudId) {
this.cloudId = cloudId;
};
TagCloud.prototype.createTagCloud = function(){
createTagsArray(this.cloudId);
};
return TagCloud;
}());
new TagCloud("tagcloud");
我创建TagCloud对象。我用闭包创建它,以具有一个私有函数createTagArray。然而,在这个函数中,我可以访问TagCloud构造函数-cloudId中定义的变量。当然,在这个例子中,我无法使用this获得它。但有没有办法得到它?(我不想将此值作为函数createTagArray参数传递)。
这也可能是我理解闭包用法的错误,因为我已经开始处理闭包了。
您不能通过闭包访问变量,因为您需要在TagCloud
构造函数中定义createTagsArray
函数,然后如果不将其公开,就不能再从createTagCloud
方法访问它。
但我认为你无论如何都不想访问这个变量。您想要访问实例的.cloudId
属性,为此您需要该实例。
实际上,最好将其作为参数传递——属性值或完整实例。这没什么错:
var createTagsArray = function(cloudId) {
j$("#" + cloudId + " a").each(function(index) {
//bla bla
});
}
TagCloud.prototype.createTagCloud = function(){
createTagsArray(this.cloudId);
};
使用call
,您甚至可以传递实例本身,以便可以作为this
:访问它
var createTagsArray = function() {
j$("#" + this.cloudId + " a").each(function(index) {
//bla bla
});
}
TagCloud.prototype.createTagCloud = function(){
createTagsArray.call(this);
};
从那里你甚至可以很容易地切换(来回)到半私有方法:
TagCloud.prototype._createTagsArray = function() {
j$("#" + this.cloudId + " a").each(function(index) {
//bla bla
});
}
TagCloud.prototype.createTagCloud = function(){
this._createTagsArray();
};
尝试以下代码:
function TagCloud(cloudId) {
var self = this;
self.createTagsArray = function() {
console.log(this);
}
self.cloudId = cloudId;
self.createTagCloud = function() {
self.createTagsArray()
}
return{
"cloudId": cloudId,
"createTagCloud": self.createTagCloud
}
};
var obj = new TagCloud("tagcloud");
obj.createTagCloud();
var obj = new TagCloud("TagCloudTest");
obj.createTagCloud();
相关文章:
- 如何使用此从对象访问构造函数
- JavaScript 访问函数构造函数中的“this”
- 访问谷歌登录函数 Angular 2 中的构造函数参数
- 如何在运行时访问typescript类公共属性(调试)?只有构造函数和函数是可访问的
- 在OPP JS中,您可以从构造函数访问原型函数内部声明的方法
- 扩展 pixi.js在构造函数中对访问父的属性进行精灵化
- 如何在使用构造函数进行原型设计时访问实例
- 使用 JavaScript 访问构造函数之外的方法
- 如何在嵌套原型中访问 JavaScript 构造函数变量
- 如何访问构造函数变量
- 为什么使用函数构造函数创建的 Javascript 函数无法访问在其外部定义的其他函数
- 无法从 javascript 中的原型访问构造函数的值
- 访问 IIFE 中的构造函数
- 访问构造函数中的 Angular 2 输入(属性)
- 如何在es6类构造函数中访问click事件的方法
- 如何从嵌套函数访问构造函数的方法/字段
- 使用闭包创建的私有函数如何访问构造函数中定义的变量
- 可以't在分配原型后访问构造函数
- 如何访问构造函数的原型
- 传递给构造函数的Can函数可以访问构造函数的其他属性