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

来源:互联网 发布:谷歌搜索镜像源码 编辑:程序博客网 时间:2024/06/07 15:18

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中除了创建新对象外还建立了一个临时函数。

0 0
原创粉丝点击