Prototypes and closures are the most common, most difficult to understand, and most easily regarded as two parts of the problem in JavaScript. Of course, they also have their extensions, such as scope chains, inheritance, etc. Recently, I have also read them in various ways, flipped them all, and recorded my own experiences. Writing will always make my understanding deeper. (It has nothing to do with the title, so I sighed. Every time I feel that I understand, I still gain a lot of rewards after reading it)
Let’s first talk about the New keyword in JavaScript. Usually, we use it to create an instance object of a class. In JavaScript, after instantiating the object, we inherit the attributes and methods of the class. Let's demonstrate it through the code
function Person(name){ this.name = name;}Person.age= "23";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 functionLet's take a look at this line
var person= new Person("Wang Fang");
What did new do? The following is what the job of JS engine does
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. Point obj's __proto__ to Person's prototype object prototype, and then 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 parameter "Wang Fang". It is equivalent to var result = obj.Person("Wang Fang"). After this sentence is executed, obj generates the attribute name and assigns it to "Wang Fang".
4. Determine the return value. If there is no return value or a non-object value is returned, return obj. Otherwise, the return value is returned as a new object (a bit twist, ternary operator, please check it out by yourself)
Summarize:
The main function of Javascript's new keyword is inheritance, as mentioned in the above example, but remember that Person is a function, while person is an object. As for the difference between functions and objects, I will write it again if I have time.
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.