似乎我对 JavaScript 中的计算属性很困惑。
当我定义一个对象并将其[d]作为键(作为属性键/名称)放入时,这[d]实际上是做什么的?似乎对于某些值,d它计算s = d.toString()并使用该值s作为属性键。但是对于其他值d(例如 whend是符号),它实际上使用符号的值作为键。
因此[d](作为语法结构)的这种双重行为似乎令人困惑。有人可以深入解释这是如何工作的吗?
顺便说一句,还有其他特殊情况吗?还是只有当d我们有这种特殊行为时才出现 Symbol ?
回到基础:什么东西可以是对象属性的键/名称?它只是字符串或只是字符串和符号,还是还有其他东西......?
例子:
var symbol = Symbol("test");
function Animal(name){
this.name = name;
}
Animal.prototype = {};
Animal.prototype.constructor = Animal;
function Dog(breed){
this.breed = breed;
this.name = "Dog";
this.s = symbol;
}
Dog.prototype = new Animal();
Dog.prototype.constructor = Dog;
console.log("001");
var d = new Dog("Sharo");
for (let x in d){
console.log(x, …Run Code Online (Sandbox Code Playgroud)