【问题标题】:javascript function calling performance with newjavascript函数调用性能与新
【发布时间】:2012-09-18 20:15:32
【问题描述】:

我是 javascript 和 oops 的新手。我有一个javascript函数

function foo(args){

   ...
}


//mehtod1
var type1=foo(a);

//mehtod2
var type2= new foo(a);

现在我怀疑mehtod1或method2哪个会给我们带来更多性能

new关键字的意义是什么,相比mehtod1有什么优势?

(对不起,如果问题已经存在并且我的英语很差)

【问题讨论】:

    标签: javascript jquery oop prototype


    【解决方案1】:

    第一次调用执行一个操作:函数评估。第二个执行两个:创建一个新对象,然后进行函数评估。不要使用 new 来评估函数。

    这是一个例子:

    var x = function () { return true; };
    
    var y = x(); // Type of y is boolean
    var y = new x; // Type of y is object
    var y = new x(); // Type of y is object
    var y = x; // Type of y is a function
    var y = x.call(this); // Type of y is a boolean
    

    【讨论】:

    • @icktoofay 谢谢你的纠正,你说得对。我将在一秒钟内编辑
    【解决方案2】:

    它们是不同的。

    type1 将是函数foo 的返回值。

    type2 将是一个对象,其构造函数是函数foo

    new 运算符创建用户定义对象类型的实例或 具有构造函数的内置对象类型之一。

    Reference.

    【讨论】:

      猜你喜欢
      • 2018-01-16
      • 1970-01-01
      • 1970-01-01
      • 2011-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多