作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
如何在obj 的处理程序 函数中获取变量?没有引用 MyClass 中的 obj。
var obj = {
func: function(){
var myClass = new MyClass();
myClass.handler = this.handler;
myClass.play();
},
handler: function(){
//Here i don't have access to obj
console.log(this); //MyClass
console.log(this.variable); //undefined
},
variable:true
};
function MyClass(){
this.play = function(){
this.handler();
};
this.handler = function(){};
};
obj.func();
如果您使用 Base.js 或其他类似的 oop 方式,这就是构造需要您。
_.bindAll(obj) (下划线方法)也不合适。它是 Base.js 中的 break overriding。
最佳答案
仅绑定(bind)处理程序方法:http://jsfiddle.net/uZN3e/1/
var obj = {
variable:true,
func: function(){
var myClass = new MyClass();
// notice Function.bind call here
// you can use _.bind instead to make it compatible with legacy browsers
myClass.handler = this.handler.bind(this);
myClass.play();
},
handler: function(){
console.log(this.variable);
}
};
function MyClass(){
this.play = function(){
this.handler();
};
this.handler = function(){};
};
obj.func();
关于javascript - 如何在回调中调用对象的键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10011919/
我是一名优秀的程序员,十分优秀!