ember.js计算属性中this的值是如何定义的

How is the a value of this in ember.js computed property defined?

本文关键字:何定义 定义 计算 js 属性 this ember      更新时间:2024-06-10

我试图理解为什么在计算属性中使用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,可能是undefinedwindow。Ember调用在所讨论对象的上下文(使用this)中作为计算属性的一部分指定的函数,因此很明显,使this等于undefined根本不起作用。