Home > Web Front-end > JS Tutorial > body text

Explanation on issues related to the new operator

jacklove
Release: 2018-05-21 11:02:17
Original
1399 people have browsed it

The following are some issues with the new operator. This article will explain the relevant issues.

Look at the results first

function Person (name, age, job) {  this.name = name  this.age = age  this.job = job
}
Person.prototype.sayName = function () {  console.log(this.name)
}// 使用new操作符var p1 = new Person('laoyang', '22', 'coding')
p1 instanceof Person // true// 不使用new 操作符var p2 = new Object()
Person.call(p2, 'xiaoyang', '2', 'test')
p2.__proto__ = Person.prototype
p2 instanceof Person // true
Copy after login

Compare the differences

// 使用new 操作符直接创建实例var p1 = new Person('laoyang', '22', 'coding')
// 不使用new 操作符var p2 = new Object() 
// p2 创建成为一个对象 这时p2的原型是ObjectPerson.call(p2, 'xiaoyang', '2', 'test')
 // Person构造函数在 p2 对象的环境内执行 这时p2已经是一个具有Person属性的实例了,但原型是Objectp2.__proto__ = Person.prototype 
// 最后把Person.prototype 赋值给p2.__proto__,让p2的原型指向Person.prototype
Copy after login

Steps to create an instance without using the new operator:

Person.call(p2, 'xiaoyang', '2', 'test') // d

This article shows issues related to the new operator. For more related issues, please pay attention to the PHP Chinese website.

Related recommendations:

Explanation of common JS function issues

Explanation of JavaScript related functions

Explanation about jquery DOM& events

The above is the detailed content of Explanation on issues related to the new operator. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
new
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template