javascript - 放置属性而不赋值的目的是什么?

标签 javascript

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

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

放置属性时没有为其分配任何值。我发现这是故意的,但我不知道为什么这样做。

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

最佳答案

从语言的 Angular 来看,根本没有任何东西。1这只是 JavaScript 新手“声明”实例属性的做法。它根本没有任何作用。用湿面条殴打作者的头部和肩膀。

某些工具(例如 IDE)可能会获取该信息并将其用于自动完成功能,例如,某个工具可能会看到该访问并说“啊,好的,所以这个东西有一个 variableOne,我会记住它并将其作为完成建议提供。”我建议,如果您打算这样做,也为该属性提供默认值将使意图更清晰,但这是一个风格问题。


1 ...假设 variableOnevariableTwo 未使用对原型(prototype)产生副作用的 getter 进行定义。如果它们定义为对原型(prototype)有副作用的 setter/getter ,则用更重要的东西替换湿面条。

由于有评论询问他们,这里有更多关于具有副作用的 setter/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();

关于javascript - 放置属性而不赋值的目的是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41034161/

相关文章:

javascript - 获取 DOM 中元素的当前位置

javascript - {}.toString() 未捕获语法错误 : Unexpected token

javascript - 这种默认参数和解构的特殊场景是如何工作的?

javascript - 简单的卡片翻转和缩放

javascript - 来自 Partials 的 Angular JS $scope 在 index.html 中不起作用

javascript - 在 React 中从容器移动到子容器时如何阻止 onDragLeave 触发

javascript - 向下钻取后样条曲线未绘制 - HighCharts

javascript - 一个JS函数分别翻转两个div

javascript - 如何删除 JSON 数组中的数据?

javascript - 如何在纯 Javascript 中的单选按钮上使用 addEventListener?