您的位置:首页 > Web前端 > JavaScript

使用函数创建JavaScript的类和对象

2014-01-08 15:22 141 查看
JavaScript的函数可以作为对象来使用。(发现{}对象竟然没没有prototype属性,之前怎么没注意到呢?,{}有属性__proto__)

比较Object.create()和new 函数

/**使用函数创建类*/
function Class1() {}
Class1.prototype.a = 100;//假如写Class1.a = 100;则最终a属性不会传递给新建对象

function T1() {
new Class1();
}
function T2() {
Object.create(Class1);
}
/**函数执行times次的时间,默认100万次*/
function RunTime(func, times) {
var t = new Date(),
i = 0;
times = times ? times: 1000000;
while (i++<times) {
func();
}
return (new Date()).getTime() - t.getTime();
}
console.log(RunTime(T1));
console.log(RunTime(T2));
输出结果为:16 118

所以使用函数创建对象实例更划算

为什么使用Object.create不划算呢?

Object.create = function (o) {
var F = function () {};
F.prototype = o;
return new F();
};
原来Object.create中除了创建新对象外还建立了一个临时函数。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐