Home  >  Article  >  Web Front-end  >  Explanation on issues related to the new operator

Explanation on issues related to the new operator

jacklove
jackloveOriginal
2018-05-21 11:02:171409browse

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

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

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!

Statement:
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