【问题标题】:javascript binding not takes the object instead windowjavascript绑定不接受对象而不是窗口
【发布时间】:2022-11-14 13:02:24
【问题描述】:

我的绑定方式不起作用。请纠正我。

const ob = {
  name:'arif',
  getName:() => {
    console.log(this)
    return this.name; 
  }
}
const x = ob.getName.bind(ob);
console.log(x()); //return the global name!!

【问题讨论】:

  • 箭头函数没有这个,普通函数有
  • 哦..同意。那么它是如何处理的呢?你能给世界一些KT吗?
  • 你不需要在这里创建函数的引用,你可以像ob.getName()这样简单地调用它,或者如果你想创建变量,那么你需要将函数更改为箭头函数

标签: javascript


【解决方案1】:

注意:- 即使没有绑定,只有当您直接在对象上调用它时,您的函数才会将其视为 ob。

箭头函数没有这个,普通函数有

const ob = {
  name:'arif',
  getName: function(){
    console.log(this)
    return this.name; 
  }
}
const x = ob.getName.bind(ob);
console.log(x()); 

【讨论】:

  • 请检查我的评论。如果可能的话,提供一些关于这个问题的信息
【解决方案2】:

箭头函数没有自己的参数属性,绑定将与箭头函数失败。

相反,您可以在此处使用普通功能:

 const ob = {
  name:'arif',
  getName: function() {
    console.log(this)
    return this.name; 
  }
}
const x = ob.getName.bind(ob);
console.log(x()); //returns the object name !!

【讨论】:

    猜你喜欢
    • 2020-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-08
    • 2017-09-28
    • 1970-01-01
    • 1970-01-01
    • 2017-04-15
    相关资源
    最近更新 更多