JavaScript 通过function创建对象的思考

来源:互联网 发布:英雄联盟for mac美服 编辑:程序博客网 时间:2024/06/01 10:04

JavaScript中 function()不仅能够创建普通的函数,也可以创建复合对象(即相当于构造函数)。本文主要介绍创建复合对象的知识。

1.返回类型为单一值

var fun1 = function() {return 'this is factoryServices01';};console.log(typeof fun1); //functionconsole.log(typeof fun1()); //string,加括号后执行fun1函数

2.返回类型为复合对象

var fun2 = function() {return {name: 'kancy',play: function() {    alert('hello');},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,因为没有return;但是alert正常执行console.log(typeof fun2().address); //object//console.log(typeof fun2().address());  // 错误:"Uncaught TypeError: object is not a function"


1 0
原创粉丝点击