ember.js计算属性中this的值是如何定义的
How is the a value of this in ember.js computed property defined?
我试图理解为什么在计算属性中使用function()有效,但胖箭头无效。
这里是我创建的一个类,以及两个计算属性的定义,一个在function() {}
(foo)中传递,另一个在() => {}
条中传递。我包含了传递到数组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
这是旋转木马的链接https://ember-twiddle.com/d5905b42eff57e8ad5c99a27a3199429?openFiles=templates.application.hbs%2C
表单的函数
foo1: [1].forEach(function() {
console.log(`this in foo1 is ${this}`);
不是计算函数,正如您可能知道的那样;它们在解析时执行。forEach
返回的值是undefined
。因此,foo1
属性的值将是常数undefined
。控制台日志只会发生一次,当解析定义时,甚至在实例化Light
对象之前。
您的功能
bar: Ember.computed( 'isOn', 'color', () => {
console.log(`this in bar is ${this}`);
}),
不起作用,因为箭头函数具有词汇this
(换句话说,周围环境的this
)。this
将是解析定义时有效的this
,可能是undefined
或window
。Ember调用在所讨论对象的上下文(使用this
)中作为计算属性的一部分指定的函数,因此很明显,使this
等于undefined
根本不起作用。
相关文章:
- 用嵌套函数和默认函数定义函数
- Dojo不解析自定义小部件的模板html中的小部件声明性
- 为什么“;未定义的“;在JavaScript中结束循环
- 要求未定义JS回调参数
- 控制台返回var不是't定义,但它是
- 在自定义mean.io包中使用angular-chart.js作为依赖项
- 如何检查管道中未定义的项目
- TypeError:无法读取属性'推'未定义的JavaScript
- jQuery自定义验证比较多个输入的序列
- 查看JS对象的所有键,甚至是getter定义的键
- fetch() 函数未在 Ubuntu Chromium 浏览器上定义
- $window.ga在AngularJS事件中未定义
- 如何在JQuery函数中定义一个值,然后调用另一个函数并使用该值
- 是否有任何方法可以使用jQuery替换在数组中定义值的文本
- 未捕获的TypeError无法读取未定义的属性socialsharing
- WebDriverException:tinyMCE未在selenium Web driver java中定义
- 使用 RequireJS 加载时如何不定义“定义”
- Chrome扩展抛出"未定义"定义变量
- 如何将自定义(定义)顺序应用于DC.js中的行图的行
- Javascript/JQuery POST "url"未定义(定义)