Prototypes and closures are the most common in JavaScript, the most difficult to understand, the most easily as the problem of the two parts, of course, and their extension, such as the scope chain, inheritance, and so on, I recently also a variety of look, all kinds of turn, record points of their own experience, writing will always make their own understanding a little deeper. (with the title of the relationship is not much, the emotion sentence, each time always feel that they understand, and then turn or harvest full)
Let's talk about the new keyword in JavaScript, which is usually used to create an instance object of a class that, in JavaScript, inherits the properties and methods of the class after instantiating the object. Use the code to demonstrate
function person (name) {
this.name = name;
}
Person.age= ";
" Person.prototype.say = function () {
console.log ("I ' m" + this.name);
};
var person= new Person ("Wang Fang");
Console.log (
person.name,//Wang Fang
person.height//undefined
);
Person.say (); I ' m Wang Fang
console.log (
person.name,//person
person.age//23
);
Person.say (); Person.say is not a function
Let's take a look at this line.
var person= new person ("Wang Fang");
What did new do? Well, the work of JS engine is the following.
var obj = {};
obj.__proto__ = Person.prototype;
var result = Person.call (obj, "Wang Fang");
Return typeof result = = ' obj '? Result:obj;
1. Create a new object first
2. The __proto__ of obj points to the prototype object of person prototype, at which point the prototype chain of the Obj object is established: Obj->person.prototype->object.prototype->null
3. Call the person function in the execution space of the Obj object and pass the argument "Wang Fang". Equivalent to var result = obj. Person ("Wang Fang"). When this sentence is finished, obj produces the property name and assigns the value to "Wang Fang".
4. Determine the return value, if no return value or return a non-object value, the obj returned, otherwise the return value as a new object returned (a bit around the mouth, ternary operator, look at it yourself)
Summarize:
The New keyword of javascript is mainly about inheritance, as the example above says, but remember that person is a function, and person is an object, as for the difference between a function and an object, I have time to write it.
The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.