我在一些代码中看到这样的事情:
var MyObject = function (options) {
this.variableOne;
this.variableTwo;
};
放置属性时没有为其分配任何值。我发现这是故意的,但我不知道为什么这样做。
你能解释一下这个技术的目的吗?
最佳答案
从语言的 Angular 来看,根本没有任何东西。1这只是 JavaScript 新手“声明”实例属性的做法。它根本没有任何作用。用湿面条殴打作者的头部和肩膀。
某些工具(例如 IDE)可能会获取该信息并将其用于自动完成功能,例如,某个工具可能会看到该访问并说“啊,好的,所以这个东西有一个 variableOne
,我会记住它并将其作为完成建议提供。”我建议,如果您打算这样做,也为该属性提供默认值将使意图更清晰,但这是一个风格问题。
1 ...假设 variableOne
和 variableTwo
未使用对原型(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/