我刚接触使用带有React的ES6类,之前我已经将我的方法绑定到当前对象(在第一个示例中显示),但ES6是否允许我使用箭头将类函数永久绑定到类实例?(当作为回调函数传递时很有用.)当我尝试使用它时,我遇到错误,就像使用CoffeeScript一样:
class SomeClass extends React.Component {
// Instead of this
constructor(){
this.handleInputChange = this.handleInputChange.bind(this)
}
// Can I somehow do this? Am i just getting the syntax wrong?
handleInputChange (val) => {
console.log('selectionMade: ', val);
}
Run Code Online (Sandbox Code Playgroud)
因此,如果我要传递SomeClass.handleInputChange
给setTimeout
它,那么它将被限定为类实例,而不是window
对象.
随着2015年6月ECMAScript 6的发布,引入了Javascript类语法.
这个语法:
class Polygon {
constructor(width, height) {
this.width = width;
this.height = height;
}
}
Run Code Online (Sandbox Code Playgroud)
基本相同:
function Polygon(width, height) {
this.width = width;
this.height = height;
}
Run Code Online (Sandbox Code Playgroud)
那么使用类而不是传统函数有什么好处呢?在什么条件下我应该使用类而不是函数?
考虑以下代码:
var SomeObject = function (id) {
this.id = id;
};
SomeObject.prototype.Handler = function() { alert(this.id);};
var o = new SomeObject("bla");
$('#someDivId').on('shown.bs.modal', o.Handler);
Run Code Online (Sandbox Code Playgroud)
我期待一个弹出窗口说"bla",但我得到一个弹出窗口"someDivId".
有没有办法将实例方法用作事件处理程序?
我在JavaScript中将Class方法读作事件处理程序?并使用对象的方法作为事件处理程序,如何删除它?但我无法将它们转录到我的案子中.