Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/powerbi/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为什么TypeScript加上了";原型;?_Typescript - Fatal编程技术网

为什么TypeScript加上了";原型;?

为什么TypeScript加上了";原型;?,typescript,Typescript,我的打字脚本代码: export class File { isOpenEnabled() { return false; } openClicked() { debugger; } } define([], function () { return { handler: new File() }; }); 变成: define(["require", "exports"], function(

我的打字脚本代码:

export class File {
    isOpenEnabled() {
        return false;
    }

    openClicked() {
        debugger;
    }
}

define([], function () {
    return {
        handler: new File()
    };
});
变成:

define(["require", "exports"], function(require, exports) {
    var File = (function () {
        function File() {
        }
        File.prototype.isOpenEnabled = function () {
            return false;
        };

        File.prototype.openClicked = function () {
            debugger;
        };
        return File;
    })();
    exports.File = File;

    define([], function () {
        return {
            handler: new File()
        };
    });
});
为什么要插入原型


谢谢-javascript中的dave函数是对象

例如:

function MyClass () {

  this.MyMethod= function () {};
}
每次创建
MyClass
的新实例时,也会创建
MyMethod
的新实例。 更好的方法是将函数
MyMethod
添加到
MyClass
的原型中:

MyClass.prototype.MyMethod = function(){};
这样,无论您创建了多少个
MyClass
实例,都只会创建一个
MyMethod

回到你的问题,我认为typescript正是在对你在
文件
类中定义的方法进行这种优化。

有两个原因:

  • 内存优化(Alberto已经提到)
  • 原型遗传

第二个原因和第一个原因在下面的章节中都有详细介绍:

所以它只创建一次MyClass.prototype,然后分配给MyClass对象的所有实例?谢谢-戴夫