在JavaScript中解构对象时如何绑定方法?

Paw*_*weł 6 javascript this destructuring node.js ecmascript-6

在JavaScript中解构对象时如何绑定方法?

const person = {
  getName: function() {
    console.log(this);
  }
};

var a = person.getName;
var b = person.getName.bind(person);
var {getName: c} = person;

person.getName(); //=> {getName: [Function]}
a();              //=> window or global
b();              //=> {getName: [Function]}
c();              //=> window or global
Run Code Online (Sandbox Code Playgroud)

我要c在控制台中登录其“父”对象{getName: [Function]}

在一条销毁线中销毁一个对象时,有什么方法可以绑定所有方法?

Ils*_*dur 9

有一个使用 ES6 类的简单解决方法。您可以bind在类构造函数中使用手动设置函数的上下文。

在下面的示例中,getName()将在解构中“幸存”:

class Person {
  constructor() {
    this.getName = this.getName.bind(this);
  }

  getName() {
    console.log(this);
  }
}

const {
  getName
} = new Person();

getName(); // Person { getName: [Function: bound getName] }
Run Code Online (Sandbox Code Playgroud)


Ori*_*ori 6

您可以随时使用 getter 或代理来绑定方法get,甚至可以使用解构。

两种解决方案都通过bound在名称的开头使用String.startsWith(). 如果未绑定,该方法将在返回之前绑定。

  1. 使用 getter 将方法自动绑定到对象。这将需要每个方法都有一个getter

const person = {
  prop: 5,
  _getName: function() {
    console.log(this.prop);
  },
  
  get getName() {
    // if not bound, bind the method
    if(!this._getName.name.startsWith('bound ')) {
      this._getName = this._getName.bind(this);
    }
    
    return this._getName;
  }
};

var a = person.getName;
var b = person.getName.bind(person);
var {getName: c} = person;

person.getName(); //=> 5
a();              //=> 5
b();              //=> 5
c();              //=> 5
Run Code Online (Sandbox Code Playgroud)

  1. 使用代理将方法自动绑定到对象。为所有方法定义一次。

var handler = {
  get: function(target, prop, receiver) {
    // if method, and not bound, bind the method
    if(typeof target[prop] === 'function' && !target[prop].name.startsWith('bound ')) {
      target[prop] = target[prop].bind(target);
    }
    
    return target[prop];
  }
};

const person = new Proxy({
  prop: 5,
  getName: function() {
    console.log(this.prop);
  }
}, handler);

var a = person.getName;
var b = person.getName.bind(person);
var {getName: c} = person;

person.getName(); //=> 5
a();              //=> 5
b();              //=> 5
c();              //=> 5
Run Code Online (Sandbox Code Playgroud)


Dan*_*sky 5

不,没有办法。与对象分离的功能将失去原始上下文。而且JavaScript中的销毁没有语法可以即时处理提取的值。

  • 这将是一个很棒的功能! (2认同)

Ore*_*444 5

只需使用箭头方法:

const person = {
  getName: () => console.log(this),
};
Run Code Online (Sandbox Code Playgroud)