javascript 为什么我不能在原型函数中为“this”分配一个新值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9713323/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 07:34:17  来源:igfitidea点击:

Why can't I assign a new value to "this" in a prototype function?

javascript

提问by Philip Walton

Why can I do this:

为什么我可以这样做:

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

But I can't do this:

但我不能这样做:

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

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

这两个函数都会破坏 this 的值并将其更改为[1,2,3]但第二个会引发以下错误: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.

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

采纳答案by Greg Hewgill

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

不允许this在函数内赋值。假设您可以这样做,并且您的代码如下所示:

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?

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

.foo()在对象上调用函数的行为不应改变对象的身份。如果b突然开始引用不同的对象,而a不仅仅是因为调用了某个方法,这对于调用者来说会非常混乱。

回答by Tobias Cohen

You're confusing objects with references.

您将对象与引用混淆了。

An array is an object, when you use a literal like [1,2,3]you're making a new array.

数组是一个对象,当您像[1,2,3]创建新数组一样使用文字时。

A variable name like thisor ais a reference to an object. If it helps, imagine an object as a person, and the reference as their nickname. You can have more than one reference to the same object, for example:

变量名如thisa是对对象的引用。如果有帮助,把一个对象想象成一个人,把引用想象成他们的昵称。你可以有多个对同一个对象的引用,例如:

var a = [1,2];
var b = a;
b.push(3);
alert(a.length); // Gives "3"

Imagine if you had a friend named Sarah. You also sometimes call her "Ace". If Sarah gets a haircut one day, Ace has a haircut too, because "Sarah" and "Ace" are both different names for the same person.

想象一下,如果你有一个叫莎拉的朋友。你有时也称她为“Ace”。如果有一天莎拉理了发,艾斯也会理发,因为“莎拉”和“艾斯”对于同一个人来说都是不同的名字。

If you use a mutating array method like a.pushor a.splice(concathowever is not one!), you change the existing Array object, and astill refers to the same object. This is like getting a hair cut - you may look different, but you're still the same person.

如果您使用像a.push或这样的变异数组方法a.spliceconcat但不是一个!),您会更改现有的 Array 对象,并且a仍然引用同一个对象。这就像理发——你可能看起来不同,但你仍然是同一个人。

When you assign a reference to a new value, with a = [1,2,3], you're creating a new array, and changing ato refer to it. This is like finding a new friend with different hair, and deciding to call her Ace instead.

当您将引用分配给新值时,使用a = [1,2,3],您正在创建一个新数组,并更改a为引用它。这就像找到一个头发不同的新朋友,并决定称她为 Ace。

Now thisis a special name generated by Javascript. It's not a given name like Sarah, but more of a title, like "mother". Your mother can get a new haircut, but you can't get a new mother. Likewise, you can't change what thisrefers to from inside a function.

现在this是由 Javascript 生成的特殊名称。它不是像莎拉这样的给定名字,而更像是一个头衔,比如“母亲”。你妈妈可以换个新发型,但你不能找一个新妈妈。同样,您不能this从函数内部更改引用的内容。

回答by xdazz

You are not allowed to re-assign this. Because the thisvalue associated with an execution context is immutable.

您不得重新分配this。因为与执行上下文关联的this值是不可变的。

回答by Avenida Gez

Is it possible to change the value of this?Not by assignment, you cannot assign a value to this

是否可以更改 的值this不是通过赋值,你不能赋值给this

Your case:

你的情况:

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

But I can't do this:

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

但我不能这样做:

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

When you modify the prototype adding method foo(), the first part makes the array become empty, equals to reassign its instance.

修改原型添加方法时foo(),第一部分使数组变空,等于重新分配其实例。

For example to var a = []

例如到 var a = []

Then in the return value:

然后在返回值中:

return this.concat([1,2,3]);

Remember that concatdoes not destroys an array, it creates a new array and returns it

请记住,concat这不会破坏数组,它会创建一个新数组并返回它

Given a = ['x']and b = ['y'], c = a.concat(b)results in c = ['x','y'], and aand bremain the same as they were

给定a = ['x']and b = ['y'],c = a.concat(b)结果c = ['x','y'], aandb保持不变

Now since you are doing this inside the array

现在既然你在数组里面做这个

a=['a','b','c']

then you call a.foo();, inside awill get equal a=[], with this.splice(0, this.length);then will concatenate [ ]with [1,2,3]

然后你打电话a.foo();,里面a会得到相等a=[]this.splice(0, this.length);然后将[ ][1,2,3]

So if I say just a.foo(), in fact nothing happens outside if I do not assign the result to something, just a remains empty.

因此,如果我说 just a.foo(),实际上,如果我不将结果分配给某事,则外部不会发生任何事情,只是 a 保持为空。

If ais assigned to something

如果a被分配给某物

c = a.foo()

then cwill be [1,2,3], and astill empty [ ]

然后c将是[1,2,3]a仍然是空的[ ]

In the second part, this = [1,2,3]

在第二部分, this = [1,2,3]

It is possible to change the value of this?, not by assignment, you cannot assign a value to this

是否可以更改 this 的值?,不是通过赋值,您不能为 this 赋值