javascript - 函数和闭包可以替代 Javascript 中的类吗?

标签 javascript angularjs

<分区>

我在阅读有关 AngularJS 的文章时在新闻组中看到了以下声明:

I have to say, though, that the more I use Angular, the less interest I have in creating classes. Classes are not where javascript is at! You can do pretty much everything you need with pure functions and closures and then you don't have to worry about the troublesome "this" and "that".

谁能解释一下“闭包”是什么意思。

最佳答案

闭包是 Javascript 代码中的一种结构,在嵌套函数中,外部函数范围保留在内部函数中。

例如:

function outer(x,y){
    var t = 1;
    return function(z){
        //x, y, t from the outer function are made available to inner function
        return x + y + z + t; 
    }
}

var outer1 = outer(1,1);  //creating a closure, or an instance of a function in sense
alert(outer1(1)); //Alerts 4

var outer2 = outer(2,2);
alert(outer2(2)); //Alerts 7

The simple explanation of a Closure is that ECMAScript allows inner functions; function definitions and function expressions that are inside the function bodes of other functions. And that those inner functions are allowed access to all of the local variables, parameters and declared inner functions within their outer function(s). A closure is formed when one of those inner functions is made accessible outside of the function in which it was contained, so that it may be executed after the outer function has returned. At which point it still has access to the local variables, parameters and inner function declarations of its outer function. Those local variables, parameter and function declarations (initially) have the values that they had when the outer function returned and may be interacted with by the inner function.

Source

关于javascript - 函数和闭包可以替代 Javascript 中的类吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16098854/

相关文章:

javascript - cordova datepicker插件在angularjs中设置默认值

JavaScript parseInt 不正确的转换

javascript - Wordpress 管理区域 - TypeError : $ is not a function.(在 '$(".tab_content")', ' $' 中未定义)

javascript - AngularJS 在客户端工作吗?

asp.net - 使用 Asp.Net Web Api 实现 Angular 2

angularjs - 错误 : [$injector:unpr] Unknown provider: $q. 对 DI 语法感到困惑

css - 使用 ng-animate 时偏移占位符元素的正确方法是什么?

javascript - javascript 中的可选参数或重新排序

php - 使用 JQuery 动态地通过 ajax 发送 json 格式的帖子表单数据

javascript - 尝试使用 $rootScope 实现指令并收到 TypeError : Cannot read property '$on' of undefined