如何更改此JavaScript以使用箭头函数访问属性
我相信这可以通过使用箭头函数来解决,但我不确定如何解决。我想访问渲染函数内部的this.props。我知道我可以把它当作一个论点,但我不愿意。这是否可以使用箭头功能?如果是,我需要改变什么如何更改此JavaScript以使用箭头函数访问属性,javascript,ecmascript-6,Javascript,Ecmascript 6,我相信这可以通过使用箭头函数来解决,但我不确定如何解决。我想访问渲染函数内部的this.props。我知道我可以把它当作一个论点,但我不愿意。这是否可以使用箭头功能?如果是,我需要改变什么 class View { constructor(options) { this.options = options; } render(el, props = {}) { this.props = props; el.innerHTML = this.options.re
class View {
constructor(options) {
this.options = options;
}
render(el, props = {}) {
this.props = props;
el.innerHTML = this.options.render(el);
}
}
var Test = new View({
render() {
return `${this.props.test}`
//
// Also, tried ${props.test} in my template literal
//
}
});
Test.render(document.getElementById("main"), {
test:"123"
})
箭头函数允许您访问外部闭包的这个部分,而不是调用函数空间的这个部分。函数的定义点是将其与被调用方的变量隔离开来。箭头函数只是使上下文或this对象的大小等于它的定义闭包。因此
var that = this;
(() => console.log(that === this))();
将打印为真,而
var that = this;
(function(){console.log(that === this)})();
将打印错误
arrow函数之所以可以访问this上下文,是因为它在那里被定义,而不是因为它在那里被调用
强制上下文对象的唯一方法是使用Function.prototype.call或Function.prototype.apply箭头函数允许您访问外部闭包的this,而不是调用函数空间的this。函数的定义点是将其与被调用方的变量隔离开来。箭头函数只是使上下文或this对象的大小等于它的定义闭包。因此
var that = this;
(() => console.log(that === this))();
将打印为真,而
var that = this;
(function(){console.log(that === this)})();
将打印错误
arrow函数之所以可以访问this上下文,是因为它在那里被定义,而不是因为它在那里被调用
强制上下文对象的唯一方法是使用Function.prototype.call或Function.prototype.apply是否需要this.props=props分配?你可以吃这样的东西
类视图{
构造选项{
this.options=选项;
}
renderel,props={}{
el.innerHTML=this.options.renderprops;
}
}
var test=新视图{render:x=>`${x.test}`;
test.renderdocument.getElementByIdmain,{test:123};
您是否需要this.props=props分配?你可以吃这样的东西
类视图{
构造选项{
this.options=选项;
}
renderel,props={}{
el.innerHTML=this.options.renderprops;
}
}
var test=新视图{render:x=>`${x.test}`;
test.renderdocument.getElementByIdmain,{test:123};
你太棒了`this.options.render.callthis,el搞定了,你太棒了`this.options.render.callthis,el完成了这个任务。不,这完全不可能使用箭头函数。您正在查找this.options.render.callthis,el.Related:不,这完全不可能使用箭头函数。您正在查找this.options.render.callthis,el.Related: