为了账号安全,请及时绑定邮箱和手机立即绑定

如何在计算属性名称中解释关键字“this”?

如何在计算属性名称中解释关键字“this”?

慕盖茨4494581 2022-07-21 10:19:16
考虑以下两个示例。var obj1 = {    "a": "A",    "b": "B",    [this.a + this.b]: function(a) {return a + this.a}};console.log(obj1.AB("a"))//TypeError: obj1.AB is not a function  var obj2 = {    "a": "A",    "b": "B",    "AB": function(a) {return a + this.a}};  console.log(obj2.AB("a"))//aA  第一个示例中出现错误的原因是什么?如果关键字“this”出现在计算属性名称中,它如何解释?
查看完整描述

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


查看完整回答
反对 回复 2022-07-21
?
哔哔one

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”的值。


查看完整回答
反对 回复 2022-07-21
?
喵喵时光机

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"));


查看完整回答
反对 回复 2022-07-21
  • 3 回答
  • 0 关注
  • 234 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号