Javascript 中是否有更简洁的方法将方法绑定到对象?
Is there a terser way to bind a method to an object in Javascript?
我发现自己经常使用这种模式
object.methodname.bind(object,...)
当我需要将一个函数传递给另一个函数时,将一个方法绑定到它拥有的对象。
Javascript有更简洁的方法吗?
你应该使用原型:
在某些方面类似于c++中的类/Java/#c
function Person(name, phone){ //constructor
this.name = name;
this.phone = phone;
}
Person.prototype.someMethod = function(){
return this.name + ' ' + this.phone;
}
并创建 Person
的实例是这样完成的:
var john = new Person('John', '123456789');
console.log(john.someMethod());
在 ES5 中,您所写的是将对象的方法绑定到自身的最简洁的方法。
有人提议 ES2016(né ES7)新 this-binding syntax
Promise.resolve(123).then(::console.log);
$(".some-link").on("click", ::view.reset);
一元形式 ::foo
是 shorthand for foo.bind(foo)
,而二进制形式 bar::foo
是 shorthand for foo.bind(bar)
虽然 ES2016 尚未以最终形式存在,但您现在可以通过 Babel plugin, either by itself or as part of preset stage 0.
使用此语法
我发现自己经常使用这种模式
object.methodname.bind(object,...)
当我需要将一个函数传递给另一个函数时,将一个方法绑定到它拥有的对象。
Javascript有更简洁的方法吗?
你应该使用原型:
在某些方面类似于c++中的类/Java/#c
function Person(name, phone){ //constructor
this.name = name;
this.phone = phone;
}
Person.prototype.someMethod = function(){
return this.name + ' ' + this.phone;
}
并创建 Person
的实例是这样完成的:
var john = new Person('John', '123456789');
console.log(john.someMethod());
在 ES5 中,您所写的是将对象的方法绑定到自身的最简洁的方法。
有人提议 ES2016(né ES7)新 this-binding syntax
Promise.resolve(123).then(::console.log);
$(".some-link").on("click", ::view.reset);
一元形式 ::foo
是 shorthand for foo.bind(foo)
,而二进制形式 bar::foo
是 shorthand for foo.bind(bar)
虽然 ES2016 尚未以最终形式存在,但您现在可以通过 Babel plugin, either by itself or as part of preset stage 0.
使用此语法