【发布时间】:2016-08-05 10:50:42
【问题描述】:
我试图理解为什么在计算属性中使用 function() 有效,但粗箭头却无效。
这是我创建的一个类,以及两个计算属性的定义,一个传入function() {} (foo),另一个传入() => {} bar。我将两种样式都包含在一个数组 forEach() 中以供参考(foo1 和 bar1)。
有人能解释一下这四种情况的每一种情况吗?
import Ember from 'ember';
const Light = Ember.Object.extend({
isOn: false,
color: 'red',
foo: Ember.computed( 'isOn', 'color', function() {
console.log(`this in foo is ${this}`);
}) ,
foo1: [1].forEach(function() {
console.log(`this in foo1 is ${this}`);
}) ,
bar: Ember.computed( 'isOn', 'color', () => {
console.log(`this in bar is ${this}`);
}),
bar1: [1].forEach( () => {
console.log(`this in bar1 is ${this}`);
})
});
export default Ember.Controller.extend({
appName: 'Ember Twiddle',
init() {
this._super();
this.set('bulb', Light.create());
}
});
这里是引用所有 4 个属性的模板
<h1>Welcome to {{appName}}</h1>
<br>
<br>
{{outlet}}
<br>
<br>
<p> the bulb is {{bulb.isOn}} </p>
<p> the bulb is {{bulb.foo}} </p>
<p> the bulb is {{bulb.foo1}} </p>
<p> the bulb is {{bulb.bar}} </p>
<p> the bulb is {{bulb.bar1}} </p>
这是打印到控制台的结果。
DEBUG: -------------------------------
VM66 ember.debug.js:6395 DEBUG: Ember : 2.4.4
VM66 ember.debug.js:6395 DEBUG: Ember Data : 2.4.3
VM66 ember.debug.js:6395 DEBUG: jQuery : 1.11.3
VM66 ember.debug.js:6395 DEBUG: -------------------------------
VM70 about:srcdoc:29 this in foo1 is undefined
VM70 about:srcdoc:35 this in bar1 is undefined
VM70 about:srcdoc:26 this in foo is <(unknown mixin):ember360>
VM70 about:srcdoc:32 this in bar is undefined
这里是 twiddle 的链接 https://ember-twiddle.com/d5905b42eff57e8ad5c99a27a3199429?openFiles=templates.application.hbs%2C
【问题讨论】:
标签: javascript ember.js