Jon*_*002 5 javascript oop prototype typescript
我可能会误会,但是在操场上看打字稿时,我注意到它们将类的方法和对象变量包装在一起,感觉每次我调用一个新对象时,它可能会降低性能。
例如Class的Typescript游乐场输出
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);
Run Code Online (Sandbox Code Playgroud)
我觉得如果我编写大量方法,那么每次我从类中创建一个新对象时,我也会编译这些大量方法。
创建新对象时,无需在函数名称之外声明方法。
例如老方法:
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);
Run Code Online (Sandbox Code Playgroud)
任何人都可以澄清是否:
答:在打字稿示例中,我正在内存中加载4种类型的函数(或由于使用了原型而覆盖了它们-我对原型的理解仍然有些动摇)。
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;
}Run Code Online (Sandbox Code Playgroud)
与
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;
}());Run Code Online (Sandbox Code Playgroud)