JavaScript对象直接量3种创建对象方式

来源:互联网 发布:怎么才能做淘宝直播 编辑:程序博客网 时间:2024/05/19 17:27

本文主要介绍JavaScript对象直接量3种创建对象方式。

以下三种方式创建的对象,达到的效果等效

方式一

var fun2 = function() {return {name: 'kancy',play: function() {alert(this.name);},address: {}};};console.log(typeof fun2); //functionconsole.log(typeof fun2()); //objectconsole.log(typeof fun2().name); //string//console.log(typeof fun2().name());  // 错误:"Uncaught TypeError: string is not a function"console.log(typeof fun2().play); //functionconsole.log(typeof fun2().play()); //undefined,因为没有returnconsole.log(typeof fun2().address); //object//console.log(typeof fun2().address());  // 错误:"Uncaught TypeError: object is not a function"

方式二

var fun4 = function() {this.name= 'kancy';this.play= function() {alert(this.name);},this.address={}return this; //一定要加上return,否则和其他两种方式效果不同};console.log(typeof fun4); //functionconsole.log(typeof fun4()); //objectconsole.log(typeof fun4().name); //stringconsole.log(typeof fun4().play); //functionconsole.log(typeof fun4().play()); //undefined,因为没有returnconsole.log(typeof fun4().address); //objectvar q1 = new fun4();q1.name="q1";console.log(q1.name);q1.name="q2";var q2 = new fun4();console.log(q2.name);

方式三

var fun5 = function() {var obj ={};obj.name= 'kancy';obj.play= function() {alert(this.name);//等同于alert(obj.name);},obj.address={}return obj;};console.log(typeof fun5); //functionconsole.log(typeof fun5()); //objectconsole.log(typeof fun5().name); //stringconsole.log(typeof fun5().play); //functionconsole.log(typeof fun5().play()); //undefined,因为没有returnconsole.log(typeof fun5().address); //object


1 0