【问题标题】:How to create an object from javascript function如何从javascript函数创建对象
【发布时间】:2018-10-01 11:22:45
【问题描述】:

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

我遇到的问题是,似乎以下两个都做同样的事情。我的研究没有表明存在什么(如果有的话)差异,但这可能是因为很难在搜索框中质疑这一点。

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

<!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 这个词。我的问题是,这真的有影响吗?

【问题讨论】:

  • @CRice 是不是也一样,因为我看到的区别是我的例子,使用了new这个词。当然,我很高兴接受这个骗局(并且为了记录,我首先进行了 Google 搜索),但如果能确定这一点,那就太好了,也让人放心

标签: javascript


【解决方案1】:

new 采取的步骤是 (from MDN):

  1. 创建了一个新对象,继承自 Foo.prototype。
  2. 使用指定的参数调用构造函数 Foo,并将 this 绑定到新创建的对象。新 Foo 是 等效于 new Foo(),即如果没有指定参数列表,则 Foo 为 不带参数调用。
  3. 构造函数返回的对象成为整个new表达式的结果。如果构造函数没有 显式返回一个对象,使用第一步创建的对象 反而。 (通常构造函数不返回值,但它们可以 如果他们想覆盖正常的对象创建,请选择这样做 过程。)

此时您使用函数表达式或函数声明并不重要;只是你使用了一个函数。

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】:

    你可能会觉得这很有趣。

    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...?

    【讨论】:

      猜你喜欢
      • 2023-03-24
      • 2016-07-11
      • 2012-04-07
      • 1970-01-01
      • 2015-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多