将方法名称作为回调传递 VS.用匿名函数包装它

2023-12-01

我有一个按钮#test。

var obj = {
  name: "John",
  test: function() {
    console.log('name '+ this.name );
  }
};

$("#test").on( "click", obj.test);

这将记录一个空字符串(记录 typeof this.name 给出一个字符串)。

编辑:我明白了thiscontext 成为按钮,因此 this.name 不返回任何内容。

Versus

var obj = {
  name: "John",
  test: function() {
    console.log('name '+ this.name );
  }
};

$("#test").on( "click", function() {
  obj.test();  //logs John
});

有什么不同?

编辑:用 annon 函数包装 obj.test() 如何使其行为与上面不同?


这是关于解决this。如果你使用$("#test").on("click", obj.test); then this将是按钮,但如果你通过closure then thisobj.

当我调用 obj.test 时this在测试中将是 obj.

JQuery 将设置this成为单击时的按钮,因此传递 obj.test 而不引用 objthis会破坏你的 obj.test 函数。

解决这个问题的最好方法是使用函数.原型.bind(你需要polyfil对于 IE

var obj = {
    name: "John",
    test: function () {
        console.log('This is:' + this.toString());
    },
    toString: function () {
        return "It's test"
    }
};

$("#test").on("click", function () {
    // by the way; this here is the button
    console.log("what's this here:", this.toString());
    obj.test();  //works but creates a closure
});

$("#test").on("click", obj.test);//breaks, this will be button in test

$("#test").on("click", obj.test.bind(obj));//works

// now to show how this is resolved
window.mytest = obj.test;
window.mytest();// this is window
var obj2 = {
    toString: function () {
        return "this is obj2";
    }
};
obj2.test = obj.test;
obj2.test();//this is obj2
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将方法名称作为回调传递 VS.用匿名函数包装它 的相关文章

随机推荐