Home  >  Article  >  Web Front-end  >  Use of new in javascript_javascript skills

Use of new in javascript_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:31:541042browse

So there is no concept of class in javascript. It is important to understand this. In order to make it easier for readers to understand, many JavaScript tutorials will apply concepts from their commonly used class patterns, which will cause ambiguity for everyone.
First segment of code,

Copy code The code is as follows:

function employee(){
this.name="";
this.dept="";
}
employee.prototype={
say:'hello'
}
var p = new employee();

We will often use this code, and the new keyword is the most confusing. The work done by new here is different from that in .NET.
We can understand the process of creating an instance using the new operation in JavaScript in this way. The new keyword creates a new object using employee() as the template, which copies the member variables in the employee constructor (it can also be understood as, The p object is passed into the constructor as a parameter, and all this member variables in the function are applied), and the prototype of the constructor is inherited.
We use code to simulate the new process.
Copy code The code is as follows:

//var p = new Object() is also correct .
var p ={};
employee.apply(p);
p.__proto__ = employee.prototype;

__proto__ is an internal property of the javascript object instance. It Points to the prototype attribute of the constructor, that is, employee. When the object looks for a member variable, such as p.say, it first looks for its own member attribute. If it is found, it returns the value. If it is not found, it calls __proto__ to check the prototype. Chain, the current example, is to find the say member in employee.prototype.
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