代码改变世界

对象创建过程(new实现原理)

2010-02-26 11:30  BlueDream  阅读(1010)  评论(0)    收藏  举报
    /**
        new操作原理(SpiderMonkey引擎下演示)
    */
    var a = function(name, age) {
        var x = 'x';
        this.name = name;
        this.age = age;
        this.say = function() {
            alert(this.name + ',' + x);
        }
    }
    a.prototype.hi = function() {
        alert(this.age);
    }

    var createInstance = function(F) {
        var p = {},
            re = null,
            args = Array.prototype.slice.call(arguments, 1);
        p.__proto__ = F.prototype;
        F.prototype.constructor = F;
        re = F.apply(p, args);
        if((typeof re === 'object' && re) || typeof re === 'function') {
            return re;
        }
        return p;
    }

    var newA = createInstance(a, 'Tom', '23');
    newA.say();
    newA.hi();
/******************************************************************************
 *    对象的创建过程(new时[[construct]]的处理逻辑)
 *    1. 创建一个build-in object对象p 并初始化
 *    2. 如果F.prototype是Object类型,则将p内部的[[prototype]]设置为F.prototype
 *     否则obj的[[prototype]]将为其初始值不需要指定(即Object.prototype).
 *    3. 将p作为this,使用args参数调用F的内部[[Call]]方法.
 *     3.1 内部[[Call]]方法创建当前执行上下文
 *     3.2 调用F的函数体 
 *     3.3 销毁当前的执行上下文
 *       3.4 返回F函数体的返回值.如果F的函数体没有返回值则返回undefined
 *    4. 如果[[Call]]的返回值是Object类型,则返回这个值,否则返回p     
 ******************************************************************************/

 

 

附一张对象模型的好图