zoukankan      html  css  js  c++  java
  • 【转】js 关于new的讨论

    一直不清楚new到底是怎么样的操作
    看了winter那个理解面向对象总算有些明白
    为了弄清楚ecma这个天书现在也得啃了
    winter说new其实就是调用 [[Construct]]
    13.2.2 [[Construct]]
    When the [[Construct]] property for a Function object F is called, the following steps are taken:
    1.        Create a new native ECMAScript. object.
    2.        Set the [[Class]] property of Result(1) to "Object".
    3.        Get the value of the prototype property of the F.
    4.        If Result(3) is an object, set the [[Prototype]] property of Result(1) to Result(3).
    5.        If Result(3) is not an object, set the [[Prototype]] property of Result(1) to the original Object prototype object as described in section 15.2.3.1.
    6.        Invoke the [[Call]] property of F, providing Result(1) as the this value and providing the argument list passed into [[Construct]] as the argument values.
    7.        If Type(Result(6)) is Object then return Result(6).
    8.        Return Result(1).

    下面是我的理解
    例如 f = new F
    1 2大概可以理解成是建一个对象
    x = {}
    3 是
    p = F.prototype
    4 如果p是object就
    x.[[Prototype]] = p
    5 如果p不是object就
    x.[[Prototype]] = Object.prototype
    6 运行F.[[Call]](就是调用F), 并以x作为this,还有参数
    7 如果6的结果的是对象,就返回6的结果
    8 否则返回x(通常情况)

    abcdreamer发布于2009-05-30 17:58:46
    不错。
    函数比对象多的,应该就是prototype、[[Construct]]、[[Call]]。
    [[Call]]使函数可以执行,prototype和[[Construct]]为new服务,使可以创建实例。
    abcdreamer发布于2009-05-30 18:05:27

    CODE:

    <script>
    function f() {}
    alert(new f().constructor);
    f.prototype = f;
    alert(new f().constructor);
    delete f.prototype;
    alert(new f().constructor);
    </script>

    dh20156发布于2009-05-31 12:56:50

    CODE:

    <script type="text/javascript">

    /*
       new操作原理(spiderMonkey引擎下)
    */

    var a = function(sA,sH){
        var x = "x";
        this.a = sA;
        this.h = sH;
        this.say = function(){alert(this.a+','+x)}
    }
    a.prototype.hi = function(){alert(this.h)}

    var createInstance = function(source){
        var p = {}
        var args = Array.prototype.slice.call(arguments,1);
        source.apply(p,args);
        p.__proto__ = source.prototype;
        return p;
    }

    var A = createInstance(a,"A","hi A");
    A.say();
    A.hi();

    </script>

    abcdreamer发布于2009-05-31 13:00:20
    我记得是先关联prototype,然后执行构造函数啊

    CODE:

    <script>
    function f() {
      alert(this.a);
    }
    f.prototype.a = 1;
    new f;
    </script>
  • 相关阅读:
    js加载完所有的图片,适合电子相册哦~~~~
    获取路径参数的方法
    JS 对数组的常用处理
    JS date常用代码积累
    js框架设计1.4类型判断
    js框架设计1.3数组化
    js框架设计1.2对象扩展笔记
    js框架设计1.1命名空间笔记
    java 跨域
    ACM-ICPC 2018 徐州赛区网络预赛 I Characters with Hash(模拟)
  • 原文地址:https://www.cnblogs.com/jazzka702/p/1637858.html
Copyright © 2011-2022 走看看