在JavaScript中定义类?

时间:2018-11-09 05:47:22

标签: javascript typescript

我正在跟踪一个教程,在该教程中,他们使用翻译器将Typescript中的类翻译为javascript。翻译的javascript有点混乱,我想知道是否有人可以向我解释代码的作用。

原始打字稿:

class Greeter {
    greeting: string;
    constructor(message: string){
        this.greeting;
    }
    greet(){
        return "Hello, " + this.greeting;
    }
}

和翻译的Javascript:

var Greeter = (function(){
    function Greeter(message){
        this.greeting = message;
    }
    Greeter.prototype.greet = function(){
        return "Hello, " + this.greeting;
    };
    return Greeter;
}());

我对这部分感到困惑(function(){...}());

first()在做什么?为什么function(){}是必需的?以下()在做什么?

语法非常混乱,我希望有人能对此进行解释。

4 个答案:

答案 0 :(得分:2)

  

我对这部分感到困惑(function(){...}());

IIFE此功能将在浏览器解释后立即执行。您不必显式调用此函数。

  

first()在做什么?为什么function(){}是必需的?

javascript中的所有函数本质上都是Object。要创建它的实例,您必须像new Greeter()那样调用,以便正确设置上下文this。如果像Greeter()这样执行,那么上下文this就是从它执行的地方开始的。在大多数情况下,它是window对象。

参考文章

https://www.phpied.com/3-ways-to-define-a-javascript-class/

https://medium.com/tech-tajawal/javascript-classes-under-the-hood-6b26d2667677

答案 1 :(得分:1)

那叫IIFE

常规语法:

(function () {
    statements
})();

但是有时候,您可以写:

(function () {
    statements
}());

我通常使用第二个,因为它遵循以下步骤:

  • 定义函数:function () { /* statements */ }

  • 调用函数:function () { /* statements */ }()

  • 并包装函数:(function () { /* statements */ }())

或与异步线程一起使用:

(async function () {
    // await some task...
})();

(async () => {
    // await some task...
})();

您还可以使用它来定义一些局部变量,如下所示:

let Person = (function () {
    let _name = null;

    class Person {
        constructor(name) {
            _name = name;
        }
        getName() {
            return _name;
        }
    }
    
    return Person;
}());

let person = new Person('Harry');
console.log(person.getName());
console.log(window._name);

对于模块,您想要创建一些插件并使之成为全局插件,可以编写:

(function (global, factory) {
    // we can use "global" as "window" object here...
    // factory is a function, when we run it, it return "Person" class

    // try to make it global:
    global.Person = factory(); // same to: window.Person = factory();
}(window, function () {
    class Person {};

    return Person;
}));

答案 2 :(得分:0)

此构造:

const foo = (function() { })();

创建一个匿名函数,并立即调用它。结果将放入foo中。

可以使用额外的变量将其分成更多行:

const temp = function() { };
const foo = temp();

之所以打字稿这样做是因为将代码放在函数中会创建自己的新作用域。这样就可以在不更改全局名称空间的情况下做某些事情。

答案 3 :(得分:0)

Requirement already satisfied: python in /usr/lib/python2.7/lib-dynload Collecting dash==0.29.0 Exception: Traceback (most recent call last): File "/usr/lib/python2.7/dist-packages/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/usr/lib/python2.7/dist-packages/pip/commands/install.py", line 353, in run wb.build(autobuilding=True) File "/usr/lib/python2.7/dist-packages/pip/wheel.py", line 749, in build self.requirement_set.prepare_files(self.finder) File "/usr/lib/python2.7/dist-packages/pip/req/req_set.py", line 380, in prepare_files ignore_dependencies=self.ignore_dependencies)) File "/usr/lib/python2.7/dist-packages/pip/req/req_set.py", line 554, in _prepare_file require_hashes File "/usr/lib/python2.7/dist-packages/pip/req/req_install.py", line 278, in populate_link self.link = finder.find_requirement(self, upgrade) File "/usr/lib/python2.7/dist-packages/pip/index.py", line 465, in find_requirement all_candidates = self.find_all_candidates(req.name) File "/usr/lib/python2.7/dist-packages/pip/index.py", line 423, in find_all_candidates for page in self._get_pages(url_locations, project_name): File "/usr/lib/python2.7/dist-packages/pip/index.py", line 568, in _get_pages page = self._get_page(location) File "/usr/lib/python2.7/dist-packages/pip/index.py", line 683, in _get_page return HTMLPage.get_page(link, session=self.session) File "/usr/lib/python2.7/dist-packages/pip/index.py", line 792, in get_page "Cache-Control": "max-age=600", File "/usr/share/python-wheels/requests-2.12.4-py2.py3-none-any.whl/requests/sessions.py", line 501, in get return self.request('GET', url, **kwargs) File "/usr/lib/python2.7/dist-packages/pip/download.py", line 386, in request return super(PipSession, self).request(method, url, *args, **kwargs) File "/usr/share/python-wheels/requests-2.12.4-py2.py3-none-any.whl/requests/sessions.py", line 488, in request resp = self.send(prep, **send_kwargs) File "/usr/share/python-wheels/requests-2.12.4-py2.py3-none-any.whl/requests/sessions.py", line 609, in send r = adapter.send(request, **kwargs) File "/usr/share/python-wheels/CacheControl-0.11.7-py2.py3-none-any.whl/cachecontrol/adapter.py", line 47, in send resp = super(CacheControlAdapter, self).send(request, **kw) File "/usr/share/python-wheels/requests-2.12.4-py2.py3-none-any.whl/requests/adapters.py", line 423, in send timeout=timeout File "/usr/share/python-wheels/urllib3-1.19.1-py2.py3-none-any.whl/urllib3/connectionpool.py", line 643, in urlopen _stacktrace=sys.exc_info()[2]) File "/usr/share/python-wheels/urllib3-1.19.1-py2.py3-none-any.whl/urllib3/util/retry.py", line 315, in increment total -= 1 TypeError: unsupported operand type(s) for -=: 'Retry' and 'int' IIFE (Immediately Invoked Function Expression)

的一种形式

例如:

(function() { ... }());

结果等于

var Greeter = (function(){
    return 1;
}());

执行上述代码后,function fn() { return 1; } var Greeter = fn(); 的值为Greeter。但是前者使用匿名函数,而后者则声明了变量1来存储该函数。

fn

此代码段旨在在对象Greeter.prototype.greet = function(){ return "Hello, " + this.greeting; }; 的原型上定义一个函数,以便在创建Greeter时可以继承此函数。您可以参考Object.prototype