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
165 views
in Technique[技术] by (71.8m points)

Initialize this.variable_name in javascript function

I have a javaScript function with the name foo. x is a global variable that we increase in this function. then I put this.x = x and return function. then I defined a variable bar = new new foo(). after running this code, the value of bar.x is undefined. but why?

var x=0;
function foo(){
  x++;
  this.x = x;
  return foo;
}
var bar = new new new foo;
console.log(bar.x);
question from:https://stackoverflow.com/questions/65640808/initialize-this-variable-name-in-javascript-function

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

1 Reply

0 votes
by (71.8m points)

The behavior of your code is a direct result of the nature of JS Constructors and the new operator. Also, it is behaving as expected. I assume, however that your question is merely theoretical because I don't really see a valid use case for chaining multiple new operators.

In your code, foo is a Constructor, and its only purpose is to specify the type of instance that should be created. In other words, its form/structure.

When you use the new operator on a Constructor, it creates a plain blank object and links to it the Constructor function (instance.constructor), then it assigns this newly created object to the this context of the function and runs it.

If the function returns an object, then new returns that object too! If not, then new automatically returns that first created object (this).

In your case, you are returning a reference to your own Constructor. That is an object. So, new foo; is always returning a constructor. That is why you are allowed to chain multiple new operators, which is not possible when using a standard constructor.

To obtain the value of x, you must return this inside your constructor or not return an object at all.

Hope this clarifies the inner mechanics of it.

Oh! And despite general knowledge, the use of () when using new operator is not necessary.

Finally, to close the ring, please see the following snipped, using your code:

let x = 0;

function Foo(c){
  x++;
  
  this.x = x;
  
  return c ? this : Foo;
}

new new new new new new new new new Foo;

const bar = new Foo(1);

console.log(bar.x); // EXPECTED TO PRINT 10.

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

...