Creating an object can be done using an object literal:
var stu = { name: "Zhang San" , sayname:function(){ console.log(this.name); }
However, if we want to create multiple stu objects, we can't repeat the above code many times, right?
We can use the simplest factory function that returns an object:
function stuFactory (name){ return { name:name, sayname:function(){ console.log(this.name); } } } // Generate instance objects like this var stu1 = stuFactory("Zhao Si" ); var stu2 = stuFactory("Wang Wu");
But there is a problem with this, who created these two objects?
More elegant way: Constructor
The so-called constructor needs to create an object by means of new Constructor().
function stuMaker(){ this.name = name, this.sayname = function(){ console.log(this.name); } } var stu3 = new stuMaker("Nicholas" ); var stu4 = new stuMaker("Nicholas-Zhao Si");
What happened to this new keyword?
function stuMaker(){ // Create a temporary object var instacne = {}, // The instance is bound to this this = instacne, this .name = name, this .sayname = function (){ console.log(this.name); } // return this return this ; }
The summary is:
-
Create a temporary object to save the instance
-
point this to the temporary object
-
return this object
However, this is not very elegant. If the student object has a common attribute, every time an instance object is created, the common attribute will be created once, which is unreasonable. In order to solve this problem, JavaScript stipulates that each function has a prototype Attribute, what can this attribute do?
This attribute can point to a constructor object, which has an attribute constructor that points to the constructor
function constructor(){ prototype:constructor // Simple writing is such an object: constructor{constructor::constructor} }
The instance object we create through this constructor has a __proto__ attribute that points to an object, which is the above:
The object pointed to by the constructor prototype
In short:
constructor.prototype === instance object.__proto__;
What's the point of doing this?
The prototype of the constructor pre-determines the common attributes, and then when creating an object, the proto attribute of the instance object can point to this object. The advantage is that the instance object can know what its common attributes are through proto.
I always feel that I still haven't fully understood the prototype of js, and it is very laborious to explain. Let's leave it like this for the time being. With a more accessible way, I'll fill in the hole again.