This paper mainly introduces 3 kinds of methods of creating objects directly in JavaScript object.
The objects created in the following three ways are equivalent to the effect that is achieved. Way One
var fun2 = function () {return
{
name: ' kancy ',
play:function () {
alert (this.name);
},
Address: {}
}; Console.log (typeof fun2); function
Console.log (typeof fun2 ());//object
Console.log (typeof fun2 (). name);//string
// Console.log (typeof fun2 (). name ()); Error: ' Uncaught typeerror:string is not a function '
Console.log (typeof fun2 (). play);//function
Console.log ( typeof Fun2 (). Play ()); Undefined because there is no return
Console.log (typeof fun2 (). Address)//object//console.log
(typeof fun2 (). Address ()); Error: ' Uncaught typeerror:object is not a function '
Mode two
var fun4 = function () {
this.name= ' kancy ';
this.play= function () {
alert (this.name);
},
this.address={
} return this
;//Make sure to add return, Otherwise the effect is different from the other two ways
};
Console.log (typeof Fun4); function
Console.log (typeof Fun4 ());//object
Console.log (typeof Fun4 (). name);//string
Console.log (typeof Fun4 (). play); function
Console.log (typeof Fun4 (). Play ());//undefined because there is no return
Console.log (typeof Fun4 (). Address) ; Object
var q1 = new Fun4 ();
Q1.name= "Q1";
Console.log (q1.name);
Q1.name= "Q2";
var q2 = new Fun4 ();
Console.log (Q2.name);
mode three
var fun5 = function () {
var obj ={};
Obj.name= ' kancy ';
obj.play= function () {
alert (this.name);//equals alert (Obj.name);
},
obj.address={
} return
obj;
Console.log (typeof fun5);//function
Console.log (typeof fun5 ())//object Console.log (typeof fun5 (
) . name); String
Console.log (typeof Fun5 ());//function
Console.log (typeof Fun5 (). Play ());//undefined, Because there is no return
Console.log (typeof Fun5 ());//object