gpt4 book ai didi

javascript - 如何在回调中调用对象的键?

转载 作者:搜寻专家 更新时间:2023-11-01 04:19:32 25 4
gpt4 key购买 nike

如何在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/

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