javascript - 通过将它们的方法包装在一起,Typescript 类对象的性能是否会变慢?

标签 javascript typescript oop prototype

我可能是错的,但通过查看 typescripts playground,我注意到他们将类的方法与对象变量包装在一起,感觉每次我调用新对象时它可能会降低性能。

例如类的 Typescript Playground 输出

var FatObject = (function () {
   function FatObject(thing) {
       this.objectProperty = 'string';
       this.anotherProp = thing;
   }
   FatObject.prototype.someMassivMethod = function () {
       //many lines of code 
       //...
       //...
       //...
       //.......................
    };
   return FatObject;
}());

var thing = 'example';
var objOne = new FatObject(thing);
var objTwo = new FatObject(thing);
var objThree = new FatObject(thing);
var objFour = new FatObject(thing);

我觉得如果我写大量的方法,每次我从类中创建一个新对象时,我也会编译这些大量的方法。

而不是在创建新对象时在函数名称之外声明方法。

例如老办法:​​

function ThinObj(thing) {
    this.anotherProp = thing;
    this.objectProperty = 'string';
}

ThinObj.prototype.someMassivMethod = function() {
    //many lines of code 
    //...
    //...
    //...
    //..................
}

const thing = 'example'
let objOne = new ThinObj(thing);
let objTwo = new ThinObj(thing);
let objThree = new ThinObj(thing);
let objFour = new ThinObj(thing);

谁能澄清一下:

答:我在 typescript 示例中将 4 种类型的函数加载到内存中(或者由于使用原型(prototype)而覆盖它们 - 我对原型(prototype)的理解仍然不稳定)。

B:如果 Typescript 将这些方法包装在一起会产生更多的编译器工作?

谢谢

最佳答案

闭包仅在创建类本身时执行。这被称为立即调用的函数表达式 (IIFE),可以在函数关闭 } 后通过特征 ()))() 识别.

这意味着它只执行一次,因此您不必担心它的性能(总的来说,函数比人们想象的要便宜)。

此外,这种类生成模式是常见且惯用的,因为它将类的定义封装在单个表达式中。

重要的是,还需要正确转译不是 TypeScript 功能而是 ECMAScript 功能的类。根据 ES2015 规范(添加类功能的标准),类定义不会被提升,但函数定义一直是,所以正确的翻译确实是将 IIFE 结果分配给 var

用代码来说明这一点:

console.log(ThinObj);
// Does not cause an error and thus violates the specification for ES2015 classes
var t = new ThinObj('thing'); // Succeeds because function is hoisted

function ThinObj(thing) {
  this.thing = thing;
}

对比

console.log(ThinObj);
// Causes an error and therefore complies with the specification for ES2015 classes
var t = new ThinObj('thing'); // Fails because var is `undefined` before initialization

var ThinObj = (function ThinObj() {
  function ThinObj(thing) {
    this.thing = thing;
  }
  return ThinObj;
}());

关于javascript - 通过将它们的方法包装在一起,Typescript 类对象的性能是否会变慢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44314040/

相关文章:

iphone - 在类之间传递数据/异步请求/iOS

java - 线程安全和不变的关系

java - 为什么 Chrome 开发者工具和 JSFiddle 在 Javascript 控制台中不包含类和 void?

javascript - AngularJS 条件 ng-if 显示保存和更新按钮

类型上不存在 Angular2 属性

javascript - 我应该在没有转译器的 Node.js 项目中使用哪个 TypeScript 目标和库?

javascript - 逐列二维数组解构

javascript - 动态添加子项时如何设置父项可滚动

visual-studio - typescript 2.0 无输出

java - 如何在 Java 中创建类存储库以及我真的需要它吗?