Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
198 views
in Technique[技术] by (71.8m points)

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

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

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.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

A variable name like this or a is 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:

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.

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

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

Now this is 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 this refers to from inside a function.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...