Creating an object can be done by means of an object literal:
var stu = { name:"Zhang San", sayname:function() { Console.log ( This . Name); }
However, we have to create more than one Stu object can not write the above code repeatedly repeated it?
We can use the simplest factory function to return an object:
function stufactory (name) { return { name:name, sayname:function() { Console.log (this. Name); }} // This generates the instance object var stu1 = stufactory ("Zhao Si"); var stu2 = Stufactory ("Harry");
But there's a question of who created the two objects?
A more elegant way: constructors
The so-called constructor, you create the object by means of new Constructor ().
function Stumaker () { this}name = name, thisfunction() { Console.log (this. name); } var New Stumaker ("Nicholas"varnew Stumaker ("Nicholas-Zhao Four");
What happened to this new keyword?
functionStumaker () {//Create a temporary object varInstacne = {}, //instance 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 save instance
Point this to the temporary object
Return this object
However, this is not very elegant, if the student object has a common attribute, each time the creation of an instance object, it will create a common attribute once, unreasonable, JavaScript in order to solve this problem, the rule that each function has a Prototype attribute, this property can do?
This property can point to an constructor object that has a property constructor point to the constructor
function Constructor () {// Simple Write is an object: Constructor{constructor:: Constructor} }
The instance object that we created with this constructor has a __proto__ property pointing to an object, which is the object above:
The object that the constructor prototype refers to
Simply:
constructor. prototype = = = Instance object. __proto__;
What's the point of doing this?
The prototype of the constructor is to make a common attribute, and then create the object, and then let the proto attribute of the instance object point to this object, the advantage is that the instance object can know by proto what the common attributes are.
Total feeling still can not thoroughly understand JS prototype, explain very laborious, for the moment, have a more easy-to-understand way, then come to pits.
JavaScript Prototype understanding