JavaScript 通过function创建对象的思考
程序员文章站
2024-03-18 21:15:58
...
JavaScript中 function()不仅能够创建普通的函数,也可以创建复合对象(即相当于构造函数)。本文主要介绍创建复合对象的知识。
1.返回类型为单一值
var fun1 = function() {
return 'this is factoryServices01';
};
console.log(typeof fun1); //function
console.log(typeof fun1()); //string,加括号后执行fun1函数
2.返回类型为复合对象
var fun2 = function() {
return {
name: 'kancy',
play: function() {
alert('hello');
},
address: {}
};
};
console.log(typeof fun2); //function
console.log(typeof fun2()); //object
console.log(typeof fun2().name); //string
//console.log(typeof fun2().name()); // 错误:"Uncaught TypeError: string is not a function"
console.log(typeof fun2().play); //function
console.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"