为什么我不能将新值分配给“this”。在原型功能? [英] Why can't I assign a new value to "this" in a prototype function?

查看:107
本文介绍了为什么我不能将新值分配给“this”。在原型功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我可以这样做:

Array.prototype.foo = function() {
    this.splice(0, this.length);
    return this.concat([1,2,3]);
}

但我不能这样做:

Array.prototype.foo = function() {
    return this = [1,2,3];
}

两个函数都会破坏它的值并将其更改为 [1,2,3] 但是第二个会抛出以下错误:未捕获的ReferenceError:赋值中的左侧无效

Both functions destroy the value of this and change it to [1,2,3] but the second one throws the following error: Uncaught ReferenceError: Invalid left-hand side in assignment

我怀疑这是因为允许赋值意味着我可能会将数组更改为其他内容(如字符串),但我希望有人知道肯定和/或有更详细的解释。

I suspect it's because allowing assignment means I could potentially change the array to something else (like a string), but I'm hoping someone out there knows for sure and/or has a more detailed explanation.

推荐答案

不允许为分配一个值在一个函数内。假设您可以执行此操作,并且您的代码类似于:

It's not permitted to assign a value to this within a function. Suppose that you could do this, and your code looked something like:

Array.prototype.foo = function() {
    return this = [1, 2, 3];
}

var a = ["beans", "rice"];
a.foo();
// a now points to an object containing [1, 2, 3]

现在,如果你这样做了:

Now, what if you did this:

var a = ["beans", "rice"];
var b = a; // b refers to the same object as a
b.foo();
// what does b refer to now? how about a?

调用函数的行为 .foo()在对象上不应更改对象的标识。如果 b 突然开始引用与 a 之外的其他对象,这对于调用者来说会非常混乱,因为某些方法是叫。

The act of calling a function .foo() on an object should not change the identity of the object. This would be very confusing for the caller if b suddenly started referring to a different object than a simply because some method was called.

这篇关于为什么我不能将新值分配给“this”。在原型功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆