We can create objects through constructor functions (called constructors):
function She () { this. Child = ' Jon ';}
In order to use this function to create an object, we need to use the new operator, for example:
var New // Jon
The advantage of creating an object with a constructor is that she can accept some parameters, so let's change the example above:
function Her (name) { this. Name = name; this. Child = 'Jon; This.whoareyou = function () { ' I am ' + this.name + ' My child is ' + this.child; }}
Now we can use the same constructor to create different objects:
var New Her (' A '); var New Her (' B ');
As a rule, we should capitalize the first letter of the constructor in order to differentiate the general function.
If we ignore the new operator when we call a constructor, though the code will not go wrong, her results are often unexpected!
var a = Her (' A '); Console.log (typeof a); // undefined
Since we don't use the new operator, we're not creating a new object. This function call does not differ from other functions, where a should be the return value of the function, since her () function does not have an explicit return value (return keyword returned), so it implicitly returns the undefined and assigns the value to a.
So who is this at this point? The answer is window.
When we create the object, it is actually given a special property of the object---the constructor attribute (constructor prototype). This property is actually a reference to the constructor function that was used to create the object.
function She () { this. Name = ' Anna ';} var New Her (); Cosole.log (she.constructor); // function Her () {// this.name = ' Anna '; // }
Of course, because the constructor function refers to a function, we can use her to create another new object:
var New Her.constructor ()
The idea is: ' We can use her to create another object, whether or not the object HER2 has been created. '
In addition, if the object was created in this way through ' {} ', then in fact she was created by the built-in function object () function:
var o = {};console.log (o.constructor); // function Object () {}Console.log (typeof// function
instanceof operator
You can test whether an object was created by a specified constructor.
function Hero () {}; var New hero (); var o =instanceof//true
Note that the function name hero is not appended (), because this is a reference to a function and not a call.
A preliminary study of JavaScript objects (i)---constructor functions