在没有分配值的情况下放置属性的目的是什么?

时间:2016-12-08 07:36:35

标签: javascript

我在一些代码中看到这样的事情:

var MyObject = function (options) {
    this.variableOne;
    this.variableTwo;
};

放置属性时不会为它们指定任何值。我发现它是故意做的,但我不知道为什么要这样做。

你能解释一下这种技术的目的吗?

2 个答案:

答案 0 :(得分:4)

从语言的角度来看,没有任何内容。 1 这只是人们对JavaScript的新手所做的事情,并宣布"实例属性。它完全没有效果。用湿面条打击作者头部和肩部。

某些工具(如IDE)可能会选择它并将其用于其自动完成功能,例如,工具可能会看到该访问权限说"啊,好吧,所以这件事有一个variableOne,我会记住这一点并将其作为完成建议提供。"我建议如果您要这样做,为该物业提供默认值也会使意图更清晰,但这只是一种风格问题。

1 ...假设variableOnevariableTwo未定义为对原型具有副作用的getter。如果 定义了带有副作用的吸气剂,请将湿面更换为更重要的东西。

由于有评论询问他们,这里更多关于有副作用的吸气剂(在评论中):



// Using class syntax for brevity, but transpiling is enabled so
// it'll work even if your browser doesn't support them yet

// Here, we have a property on the prototype with a getter.
// This is absolutely fine and normal.
class Person {
  constructor(first, last) {
    this.first = first;
    this.last = last;
  }
  // The getter
  get fullName() {
    return (this.first + " " + this.last).trim();
  }
}
const joe = new Person("Joe", "Bloggs");
console.log(joe.fullName); // "Joe Bloggs"

// Here, we have a property on the prototype with a getter
// *with side effects*. This is a Bad Thing™.
class Thingy {
  constructor(info) {
    this.counter = 0;
    this.info = info;
  }
  // The getter with side effects. It should be a method,
  // not a getter. Getters shouldn't have side effects.
  get something() {
    ++this.counter;
    return this.info;
  }
}
const t = new Thingy("foo");
console.log(t.something, t.counter); // foo 1
console.log(t.something, t.counter); // foo 2 -- ?!?! What changed counter?!

// Here, we have a property on the prototype with a getter
// with side effects where the constructor relies on the side
// effect. This is a Very Bad Thing™. Side effects are bad
// enough, but side effects of hidden operations (a getter is
// a hidden method call) are a maintenance nightmare.
class Wrong {
  constructor() {
    this.magic;
  }
  // The getter with side effects
  get magic() {
    this.nowWeAreReallyInitialized = true;
    return "magic";
  }
  doSomething() {
    if (!this.nowWeAreReallyInitialized) {
      throw new Error("We're aren't initialized!");
    }
    console.log("Doing something");
  }
}
const w = new Wrong();
// The only reason doSomething works is that the property accessor
// for `magic` was accessed from the constructor. This is wrong.
// Wrong wrong wrong. :-)
w.doSomething();




答案 1 :(得分:1)

这样他们就会打电话给吸气鬼。也许getter在第一次调用时会做一些初始化,在构造函数中完成这项工作很重要。



var MyObject = function (options) {
    this.variable;
};
Object.defineProperty(MyObject.prototype, 'variable', {
  get: function() {
    console.log('Getter called');
  }
});
new MyObject();