3 回答
TA贡献1790条经验 获得超9个赞
如果您查看计算属性名称
您可以看到您可以在括号内放置一个表达式,这可能会导致以下构造 [(console.log(x),x)]返回x,但允许我们转储它之前保存的内容。
const a = {
[(console.log('log:', this.a + this.b), this.a + this.b)]: 'test'
}
// this.a is undefined and summing them is NaN
console.log(a.NaN) // 'test'
如果我们现在考虑下面
;(function () {
const a = {
[(console.log('log', this.a + this.b), this.a + this.b)]: 'top'
}
console.log(a.zz) // 'top'
}).call({ a: 'z', b: 'z' })
我们确实得到了一些 zztop。
我还没有阅读所有规范,但在某种程度上我们可能会依赖正在运行的执行上下文来确定this
第一种情况:全球环境
在后面:已绑定的函数{a: 'z', b: 'z'}
因为我们有点贪心:
window.a = 'z'
window.b = 'z'
const c = {
[(console.log('log', this.a + this.b), this.a + this.b)]: 'test'
}
console.log(c.zz) // 'test'
编辑:关于this函数中的。它与用于计算属性名称的表达式无关,并且过着它的生活this
const a = {
hello: 'top',
zz: function () { console.log(this.hello) } // top
}
a.zz()
// the first this is resolved as the global env
// the this in function is resolved as b
const b = {
hello: 'top',
[(console.log('the this.hello is undef', this.hello), 'zz')]: function () { console.log(this.hello) } // top. The caller is b.
}
b.zz()
// and some usual invocation where this is bound to a
const c = {
hello: true,
['zz']: function () { console.log(this.hello) } // top
}
a.hello = 'TOP'
c.zz.call(a) // TOP
TA贡献1854条经验 获得超8个赞
首先,我们不应该像这样创建 JS 对象的属性:
[this.a + this.b]: function(a) {return a + this.a}.左侧必须是主叫名称。另一方面, 的值this取决于函数的调用方式(运行时绑定)。执行时不能通过赋值来设置,每次调用函数时可能都不一样。在第二个例子中:
"AB": function(a) {return a + this.a}在这里,您调用了 return a(这将是传递给函数的参数)+ this.a。这里 this 指的是 obj2 及其属性“a”的值。
TA贡献1846条经验 获得超7个赞
您不能像这样分配键
不,如果您检查下面的代码,您可以看到您的功能键是 NaN
您正在尝试添加两个未定义的键,这就是它显示的原因NaN
请记住它Object不是constructor
var obj1 = {
"a": "A",
"b": "B",
[this.a + this.b]: function(a) { return a + this.a }
};
console.log(obj1);
现在要解决您的问题,您可以
首先创建对象并添加 foo
var obj1 = {
a: "A",
b: "B",
};
obj1[obj1.a + obj1.b] = function(a) { return a + this.a };
console.log(obj1.AB("a"));
添加回答
举报
