热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

为什么要在匿名函数()调用中嵌入JavaScript类?-WhyembedtheJavaScriptclassinananonymousfunction()call?

IwasreadingaboutthenewJavaScript-likelanguagefromMicrosoftcalledTypeScript.Intheplaygr

I was reading about the new Javascript-like language from Microsoft called TypeScript. In the playground (example section), there is a simple class in TypeScript syntax converted to Javascript code. Coming from a Java programming background, it was interesting for me to learn how OOP is done in Javascript as compiled from TypeScript.

我正在阅读微软称为TypeScript的类似Javascript的新语言。在操场(示例部分)中,TypeScript语法中有一个简单的类转换为Javascript代码。来自Java编程背景,我很有兴趣了解如何在使用TypeScript编译的Javascript中完成OOP。

The TypeScript code:

TypeScript代码:

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

var greeter = new Greeter("world");

var button = document.createElement('button')
button.innerText = "Say Hello"
button.Onclick= function() {
    alert(greeter.greet())
}

document.body.appendChild(button)

And the equivalent Javascript code:

和等效的Javascript代码:

var Greeter = (function () {
    function Greeter(message) {
        this.greeting = message;
    }
    Greeter.prototype.greet = function () {
        return "Hello, " + this.greeting;
    };
    return Greeter;
})();
var greeter = new Greeter("world");
var button = document.createElement('button');
button.innerText = "Say Hello";
button.Onclick= function () {
    alert(greeter.greet());
};
document.body.appendChild(button);

The Typescript part is very similar to Java so I understand that. Now my question is why in Javascript the body of the Greeter class is embedded in a an anonymous function() call?

Typescript部分与Java非常相似,所以我理解。现在我的问题是为什么在Javascript中,Greeter类的主体嵌入在匿名函数()调用中?

Why not write it like this?

为什么不这样写呢?

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

What is the advantage/disadvantage of each method?

每种方法的优点/缺点是什么?

6 个解决方案

#1


14  

The following is called an Immediately Invoked Function Expression:

以下称为立即调用的函数表达式:

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

It is used to keep the global scope clean. Though, in this case it isn't necessary since the return value is assigned to a variable Greeter. The only time this pattern is useful is when you want "private" static members.

它用于保持全局范围的清洁。但是,在这种情况下,由于返回值被赋值给变量Greeter,因此没有必要。此模式唯一有用的时间是您想要“私有”静态成员。

E.g.:

例如。:

var Greeter = (function () {
    var foo = 'foo', bar = 'bar'; /* only accessible from function's defined
                                     in the local scope ... */

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

#2


3  

Besides the obvious scoping/closure reasoning. Using an anonymous function that invokes itself immediately pre-loads (interprets) the class definition. This allows any JIT optimizations to be front loaded within the execution. In short, for larger more complex applications it will improve performance.

除了明显的范围/结束推理。使用调用自身的匿名函数可以预先加载(解释)类定义。这允许在执行中预先加载任何JIT优化。简而言之,对于更大更复杂的应用程序,它将提高性能。

#3


2  

The anonymous function / self executing closure is usually used to encapsulate scope so that only the returned value is accessible outside of it. (or anything you attach to other objects, like window)

匿名函数/自执行闭包通常用于封装作用域,以便只能在其外部访问返回的值。 (或任何附加到其他对象的东西,如窗口)

#4


2  

This is to allow for private members. In this example, all members are public so your two constructions are equivalent. However, if you want to provide for private members you need to hide them from the calling scope via a closure. Thus if you have a private member like so:

这是为了允许私人会员。在此示例中,所有成员都是公共的,因此您的两个构造是等效的。但是,如果要为私有成员提供,则需要通过闭包将它们隐藏在调用范围内。因此,如果您有这样的私人会员:

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

You would probably get something like this:

你可能会得到这样的东西:

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

The greeting variable will be available to any function defined inside the anonymous function, but invisible everywhere else.

greeting变量可用于匿名函数内定义的任何函数,但在其他任何地方都不可见。

#5


1  

The anonymous function is probably there to prevent name collition with other parts of the code. Think of it this way, inside your anonymous function, you could even declare a variable called "$" to be whatever you want, and at the same time, be using jQuery on other parts of your code without conflict.

匿名函数可能是为了防止名称与代码的其他部分碰撞。可以这样想,在你的匿名函数中,你甚至可以将一个名为“$”的变量声明为你想要的任何东西,同时在你的代码的其他部分使用jQuery而不会发生冲突。

#6


-4  

The closure is the sole mean to call the constructors with parameters:

闭包是用参数调用构造函数的唯一方法:

var w = new Greeter("hello")

There are other methods but all complicated and with limitations and drawbacks.

还有其他方法,但都很复杂,有局限和缺点。


推荐阅读
  • 小编给大家分享一下TypeScript2.7有什么改进,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收 ... [详细]
  • 前言小伙伴们大家好。从今天开始我们将从 ... [详细]
  • 目录实现效果:实现环境实现方法一:基本思路主要代码JavaScript代码总结方法二主要代码总结方法三基本思路主要代码JavaScriptHTML总结实 ... [详细]
  • android listview OnItemClickListener失效原因
    最近在做listview时发现OnItemClickListener失效的问题,经过查找发现是因为button的原因。不仅listitem中存在button会影响OnItemClickListener事件的失效,还会导致单击后listview每个item的背景改变,使得item中的所有有关焦点的事件都失效。本文给出了一个范例来说明这种情况,并提供了解决方法。 ... [详细]
  • 原文地址:https:www.cnblogs.combaoyipSpringBoot_YML.html1.在springboot中,有两种配置文件,一种 ... [详细]
  • 本文介绍了RPC框架Thrift的安装环境变量配置与第一个实例,讲解了RPC的概念以及如何解决跨语言、c++客户端、web服务端、远程调用等需求。Thrift开发方便上手快,性能和稳定性也不错,适合初学者学习和使用。 ... [详细]
  • Java学习笔记之面向对象编程(OOP)
    本文介绍了Java学习笔记中的面向对象编程(OOP)内容,包括OOP的三大特性(封装、继承、多态)和五大原则(单一职责原则、开放封闭原则、里式替换原则、依赖倒置原则)。通过学习OOP,可以提高代码复用性、拓展性和安全性。 ... [详细]
  • 如何搭建Java开发环境并开发WinCE项目
    本文介绍了如何搭建Java开发环境并开发WinCE项目,包括搭建开发环境的步骤和获取SDK的几种方式。同时还解答了一些关于WinCE开发的常见问题。通过阅读本文,您将了解如何使用Java进行嵌入式开发,并能够顺利开发WinCE应用程序。 ... [详细]
  • 本文讨论了在手机移动端如何使用HTML5和JavaScript实现视频上传并压缩视频质量,或者降低手机摄像头拍摄质量的问题。作者指出HTML5和JavaScript无法直接压缩视频,只能通过将视频传送到服务器端由后端进行压缩。对于控制相机拍摄质量,只有使用JAVA编写Android客户端才能实现压缩。此外,作者还解释了在交作业时使用zip格式压缩包导致CSS文件和图片音乐丢失的原因,并提供了解决方法。最后,作者还介绍了一个用于处理图片的类,可以实现图片剪裁处理和生成缩略图的功能。 ... [详细]
  • 先看官方文档TheJavaTutorialshavebeenwrittenforJDK8.Examplesandpracticesdescribedinthispagedontta ... [详细]
  • node.jsrequire和ES6导入导出的区别原 ... [详细]
  • 本文介绍了在Go语言中可见性与scope的规则,包括在函数内外声明的可见性、命名规范和命名风格,以及变量声明和短变量声明的语法。同时,还介绍了变量的生命周期,包括包级别变量和局部变量的生命周期,以及变量在堆和栈上分配的规则和逃逸分析的概念。 ... [详细]
  • QuestionThereareatotalofncoursesyouhavetotake,labeledfrom0ton-1.Somecoursesmayhaveprerequi ... [详细]
  • const限定符全解一、const修饰普通变量  intconsta500;  constinta600;  上述两种情况相同,都是声明一个const型的变量,它们 ... [详细]
  • 前言:原本纠结于Web模板,选了Handlebars。后来发现页面都是弱逻辑的,不支持复杂逻辑表达式。几乎要放弃之际,想起了Javascript中ev ... [详细]
author-avatar
mobiledu2502899415
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有