When instantiating an object in JavaScript, our common method is to use the new operator. This article mainly shares with you the detailed explanation of the new operator in JavaScript, hoping to help you.
var Foo = function(x, y) { this.x = x this.y = y }var foo = new Foo(1, 2) // Foo {x: 1, y: 2}
So what exactly does the new operator do? We can take a look at what kind of object foo is.
First of all, foo itself is an object, and then it has two attributes, x and y. At the same time, on the console of most browsers, we can also see a slightly lighter attribute called __proto__. It has two attributes, constructor and __proto__.
__proto__ is an accessor property. It points to the [[Prototype]] of the current object itself. This [[Prototype]] is not an attribute. It is just a symbol that represents the prototype object Foo.prototype of the constructor Foo. For details, please refer to ## Description on #MDN.
foo.__proto__ === Foo.prototype // true
var Foo = function(x, y) { this.x = x this.y = y }// 1. 创建一个空对象var foo = {}// 2. 调用构造函数,并且将构造函数的`this`指向fooFoo.call(foo, 1, 2)// 3. foo继承Foo的原型对象foo.__proto__ = Foo.prototype
var Foo = function(x, y) { this.x = x this.y = y return { a: this.x } }var foo = new Foo(1, 2) // {a: 1}
The difference between the new call of the js function and this in the ordinary call
About new from a Talking about BUG
What is the running process of new operator in js
The above is the detailed content of Detailed explanation of new operator in JavaScript. For more information, please follow other related articles on the PHP Chinese website!