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]}。
在一条销毁线中销毁一个对象时,有什么方法可以绑定所有方法?
有一个使用 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)
您可以随时使用 getter 或代理来绑定方法get,甚至可以使用解构。
两种解决方案都通过bound在名称的开头使用String.startsWith(). 如果未绑定,该方法将在返回之前绑定。
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(); //=> 5Run Code Online (Sandbox Code Playgroud)
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(); //=> 5Run Code Online (Sandbox Code Playgroud)
只需使用箭头方法:
const person = {
getName: () => console.log(this),
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
975 次 |
| 最近记录: |