简体   繁体   English

Javascript 函数赋值后未定义

[英]Javascript this undefined after function assignment

So I was reading the book Professional Javascript for Web developers and came across the following examples.因此,我正在阅读面向 Web 开发人员的专业 Javascript 一书,并遇到了以下示例。

var object = {
  name: "my Object",
  getName: function() {
    return this.name;
  }
}

The author then shows the following results:然后作者展示了以下结果:

object.getName(); // "my Object"
(object.getName)(); // "my Object"
(object.getName = object.getName)() // "undefined"

I understand the first case but have the following questions for case 2 and case 3.我理解第一个案例,但对案例 2 和案例 3 有以下问题。

Case 2: What does putting a parentheses around object.getName do?案例 2:在 object.getName 周围加上括号有什么作用? So far I only know that you can put parentheses around anonymous function to call it immediately (Immediately-invoked function expression).到目前为止我只知道你可以在匿名函数周围加上括号来立即调用它(立即调用函数表达式)。 But what if the function is not anonymous?但是如果函数不是匿名的呢?

Case 3: Why is this not maintained after the assignment?案例3:为什么this不是分配后保持?

The issue here really doesn't have anything to do with this changing .这里的问题确实与this变化没有任何关系。 What's different about the third case is that the value used as the function reference has lost its relationship to the context object.第三种情况的不同之处在于用作函数引用的值失去了与上下文对象的关系。

When a function reference is obtained by evaluating an object property reference, and then that function is invoked, JavaScript makes sure that this in the function is set to the object involved.当通过评估对象属性引用获得函数引用,然后调用该函数时,JavaScript 确保将函数中的this设置为所涉及的对象。 That's how the first two cases work.这就是前两种情况的工作方式。

In the third case, the function reference is originally obtained from the object, but the overall value of第三种情况,函数引用原本是从对象中获取的,但是整体的值

(object.getName = object.getName)

is the value of that = assignment.是那个=赋值的值。 Because of that, the relationship to the object is broken, and all you've got is a reference to a function.正因为如此,与对象的关系被打破了,你所拥有的只是对函数的引用。 The invocation therefore won't set this .因此调用不会设置this It's as if you'd written:就好像你写过:

var something = object.getName;
something();

That also won't set this to object .这也不会this设置为object Only when the function reference comes straight from a .仅当函数引用直接来自. or [ ] operation will the object involved end up as this in the call.[ ]操作将所涉及的对象在调用中作为this结束。 The parentheses in case 2 are sort-of a special case;情况 2 中的括号是一种特殊情况; in JavaScript, parentheses do not evaluate to anything;在 JavaScript 中,括号不计算任何值; they affect the way the expression is parsed but they don't actively do anything.它们会影响解析表达式的方式,但不会主动执行任何操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM