What is the working principle of the new operator in js, specific code examples are needed
The new operator in js is the keyword used to create objects. Its function is to create a new instance object based on the specified constructor and return a reference to the object. When using the new operator, the following steps are actually performed:
The following is a simple example to illustrate how the new operator works:
// 定义一个构造函数 function Person(name, age) { this.name = name; this.age = age; } // 使用new操作符创建一个实例对象 var person1 = new Person('Tom', 18); // 输出实例对象的属性值 console.log(person1.name); // 输出 'Tom' console.log(person1.age); // 输出 18
In the above code, we define a constructor named Person. The constructor accepts two parameters, name and age, and uses them as attributes of the instance object person1.
When using the new operator to create a person1 instance, an empty object is first created, and then the prototype of the empty object is pointed to the prototype object of the constructor Person. Next, the scope of the constructor is assigned to the empty object, so that the empty object can be accessed through this inside the constructor. Finally, the code in the constructor is executed and name and age are assigned to the properties of the new object.
Therefore, the object person1 created by the new operator has the attributes name and age defined in the constructor Person, and these attributes can be accessed through the dot operator.
It should be noted that do not explicitly return an object inside the constructor. If the constructor returns an object, the instance created by the new operator will be the returned object, not the newly created object. For example:
// 定义一个构造函数 function Person(name, age) { this.name = name; this.age = age; // 错误示例:返回一个对象 return { name: 'Error', age: -1 }; } // 使用new操作符创建一个实例对象 var person1 = new Person('Tom', 18); // 此时person1实际上是一个普通的对象,而不是Person的实例 console.log(person1 instanceof Person); // 输出 false console.log(person1.name); // 输出 'Error' console.log(person1.age); // 输出 -1
In the above example, the constructor Person explicitly returns an object, so person1 is not actually an instance of Person, but an ordinary object.
To sum up, the new operator is used to create a new instance object and initialize the properties of the object in the constructor. The instance object created through the new operator inherits the prototype object of the constructor and can access the properties and methods defined in the constructor.
The above is the detailed content of How does the new operator work in js?. For more information, please follow other related articles on the PHP Chinese website!