There are 3 common ways to create objects:
① How variables are declared
var function () {Console.log (this. key1)}}var array = [1, 2, 3];
You can continue to add properties and methods to obj1 , such as:
Obj1.color = "Red"function () {console.log ("AAA")};
② using operator new
var New Object ();
You can continue to add properties and methods to Obj2 , such as:
Obj2.name = "Madom"function () {console.log ("AAA")};
③ Creating constructors
function Cat () {
this. Age = "+"; This function () {console.log (this. Age); }}
In fact, the constructor is also a normal function, only when the new operation is the constructor,
Creates an instance object from a constructor function. Each object has its own internal prototype proto_
The individual instance objects are not the same.
var New //truevarnew/ /// Fals
Then create a constructor with return
function Bird () { this. Age =N; This function () {Console.log (' my age is ' +)}; return { ' Tim ', functionthis. name},} ;}
Create an object instance to see what's different
var New // Hello Tim// Object {name: "Tim", say:function}
Discovery: If the constructor has a return, the object instance cannot use the property and method before the constructor return
The internal operation of the new operation is generally as follows:
1th Step: Open a space in memory.
2nd step: Create a new empty object and point this to this empty object.
3rd Step: Point the internal prototype of the empty object to the prototype object of the constructor.
4th step: When the constructor execution is complete, if there is no return (returned value) , Then there is an ' implicit ' return This at the end of the constructor function If there is a return value , thereturn value is assigned to the object instance.
Perform the following simulation of the creation of the instance ( non-Real execution ):
var New Cat (); /* This = {}, * this._proto_ = Cat.prototype * this = CAT1; * Return this */
---knowledge is to share, reproduced please note the source---
JavaScript Object-oriented basics (1)