保留分配给实例方法的变量的上下文
preserve context of variable assigned to an instance method
这一直在躲避我
function tSt( val ) {
this.val = val;
}
tSt.func = function( x ) {
return x * 2;
}
tSt.prototype.func = function() {
return tSt.func( this.val );
}
var tmp = new tSt( 5 );
console.log( tmp.func()); // 10
var other = tmp.func;
console.log( other()); // undefined
我想这样做的原因是类似于以下场景:
(function( funcarr ) {
for ( var i = 0; i < funcarr.length; i++ )
console.log( funcarr[i]());
})([ tmp.func ]);
如何才能做到这一点?
更新:
这里有一个潜在的更全球化的解决方案,但我不确定这样做是否有任何缺点:
function tSt( val ) {
this.val = val;
this.func = this.func.bind( this );
}
tSt.func = function( x ) {
return x * 2;
}
tSt.prototype.func = function() {
return tSt.func( this.val );
}
使用函数#bind:
var other = tmp.func.bind(tmp);
这确保了无论何时调用other
,this
指针都将是tmp
。
由于bind
并不是在所有浏览器中都实现的,您可能需要一个类似于上面链接中给出的polyfill。(事实上,我建议你一路走,得到一个ES5垫片。)
如果你愿意放弃原型继承,如果你想在不记得bind
的情况下传递方法,这是必要的,那么我建议使用模块模式:
function TSt(val) {
// save a reference to our current "this" so that, even inside of methods
// called from other contexts, we still have it.
var that = this;
that.val = val;
that.func = function () {
return that.val * 2;
// Since we're using that instead of this, still works even without bind.
}
}
var tmp = new TSt(5);
var other = tmp.func;
console.log(other()); // 10
事实上,这种模式的另一个主要好处是可以获得私有变量:
function Encapsulated(mine, public) {
var that = this;
var private = mine * 2;
that.public = public;
that.compute = function () {
return that.public * private;
};
}
现在,Encapsulated
实例的使用者不能访问mine
或private
,而只能访问public
。
相关文章:
- 将函数的上下文应用于javascript变量
- 执行上下文和变量对象在 JavaScript 中实际上是一回事吗?
- 类方法中的上下文作为变量
- 在Ember.js中的方法之间共享变量上下文
- js脚本是否可以在同一个文件中获得在EJS上下文/页面中编写的变量
- javascript中的全局和局部变量执行上下文
- 在javascript上使用这个而不是上下文变量有什么缺点吗
- 在 Django 上下文变量上使用 Javascript 搜索算法
- 上下文的变量.填充文本
- 变量“this”上下文在重新赋值变量后未更新
- 画布的奇怪行为 上下文变量定义位置导致选项卡处于非活动状态时画布呈现冻结
- ES6 循环和 forEach 中的上下文和变量范围
- 如何在 ng-repeat 过滤器中传递 HoDjango views.py 上下文数据变量
- 使用Javascript,变量赋值上下文中的表达式与上下文外的表达式有什么区别
- 为什么公共变量的对象实例上下文丢失了,而私有变量却没有丢失
- 在Jquery中定义Django上下文变量时出错
- Handlebars模板,使用字符串键访问上下文变量
- 如何设置变量指向全局对象-独立于上下文执行
- Django.在Jquery中使用上下文变量的Json文件
- 将变量传递给函数上下文