代码之家  ›  专栏  ›  技术社区  ›  MyDaftQuestions

如何从javascript函数创建对象

  •  1
  • MyDaftQuestions  · 技术社区  · 8 年前

    我正在尝试学习对象和JavaScript。

    我的问题是,似乎以下两项都做了相同的事情。我的研究没有显示有什么(如果有的话)区别,但这可能是因为很难在搜索框中对此提出质疑。

    在代码中,我添加了注释以强调差异

    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width">
      <title>JS Bin</title>
    </head>
    <body>
    <div id = "results"></div>
      <script>
    
    "use strict";
    const results = document.getElementById("results");
    
    const Thing = function(){                /* ****** THIS */
          var _x;
          this.set = function(x){
          _x = x;
          },
    
            this.alert = function(){
                results.innerHTML += _x + "<br />";
            };
        };
    
        function Other(){                    /* ****** AND THIS */
            var _x;
          this.set = function(x){
          _x = x;
          },
    
            this.alert = function(){
                results.innerHTML += _x + "<br />";
            };
        };
    
        const t = new Thing();
        t.set("b");
        t.alert();
        const t2 = new Thing();
        t2.set("b2");
        t2.alert();
        t.alert();
        t2.alert();
    
        const o = new Other();
        o.set("d");
        o.alert();
        const o2 = new Thing();
        o2.set("d2");
        o2.alert();
        o.alert();
        o2.alert();
    
      </script>
    </body>
    </html>
    

    JSFIDDLE

    区别是什么?或者两者都有效吗?

    编辑

    我看到了副本 var functionName = function() {} vs function functionName() {} .问题之间的区别是我用的是这个词 new .我的问题是,这真的有区别吗?

    2 回复  |  直到 8 年前
        1
  •  2
  •   zero298    8 年前

    这些步骤 new takes是( from MDN ):

    1. 将创建一个新对象,继承自Foo。原型
    2. 使用指定的参数调用构造函数Foo,并将其绑定到新创建的对象。新建Foo is 等效于new Foo(),即如果未指定参数列表,则Foo为 无参数调用。
    3. 构造函数返回的对象成为整个新表达式的结果。如果构造函数没有 显式返回对象,使用步骤1中创建的对象 相反(通常构造函数不返回值,但可以 如果要覆盖正常对象创建,请选择这样做 过程。)

    在这一点上使用函数表达式或函数声明并不重要;只是你使用了一个函数。

    function Foo() {
        this.hello = "world";
    }
    
    const Bar = function() {
        this.fizz = "buzz";
    }
    
    const foo = new Foo();
    const bar = new Bar();
    
    console.log(foo instanceof Foo);
    console.log(bar instanceof Bar);
        2
  •  2
  •   Gordon Kushner    8 年前

    你可能会发现这很有趣。

    1. 您可以使用 new 启用,无论函数声明或表达式如何。

    2. 查看控制台输出。New创建函数的新实例。似乎没有任何其他副作用。

    function funcOne() {};

    var f1 = funcOne;
    var f2 = funcOne;
    
    var fx = new funcOne();
    
    console.log(funcOne==f1); //true
    console.log(f1==f2); //true
    console.log(funcOne==fx); //false
    
    const funcTwo = function(){};
    
    var f3 = new funcTwo();
    var f4 = new funcTwo();
    
    console.log(funcTwo==f3) //false
    console.log(f3==f4); //false
    

    如果您正在寻找关于函数作为对象的一些讨论,我建议您使用以下线程 javascript : function and object...?