JavaScript:self-calling函数返回一个闭包。它是什么? [英] JavaScript: self-calling function returns a closure. What is it for?

查看:220
本文介绍了JavaScript:self-calling函数返回一个闭包。它是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

学习一个构建后的JavaScript库:

Studying one JavaScript library I found following construction:

theMethod: function () {
    var m1 = new SomeClass();
    return function (theParameter) {
        this.someMethod();
        m1.methodCall(this.someField1);
        this.someField2 = 'some value';
    }
}()

theMethod被调用如下:

theMethod is called as follows:

c.theMethod(paramValue);

作者想用这个声明说什么?

What did the author want to say with this declaration?

为什么不使用这样的声明:

Why not to use such declaration:

theMethod: function (theParameter) {
    var m1 = new SomeClass();
    this.someMethod();
    m1.methodCall(this.someField1);
    this.someField2 = 'some value';
}


推荐答案

http://en.wikipedia.org/wiki/Encapsulation_%28object-oriented_programming%29 =nofollow> encapsulation 。 m1对其他方法和从可能使用方法的地方的外部访问是隐藏的。 Javascript程序员通常不关心封装(但是它们应该放在非平凡的脚本上),因为您需要使用使类的设计复杂化的闭包,并且当实现不当时可能会降低性能。这就是为什么你没有看到这种类型的结构通常在库之外。

It's for encapsulation. m1 is hidden to other methods and from external access by places that might use theMethod. Javascript programmers usually don't care about encapsulation (but they should on non-trivial scripts) because you need to use closures which complicates design of classes and when implemented poorly can reduce performance. That is why you don't see this kind of structure often outside of libraries.

你的第二个代码也不是等价的。类似的东西是:

Also your second piece of code is not equivalent. Something equivalent would be:

theMethod: function (theParameter) {
    if (typeof this.prototype.__private__ === "undefined") {
        this.prototype.__private__= {}
    }
    if (typeof this.__private__.m1 === "undefined") {
        this.prototype.__private__.m1= new SomeClass();
    }
    this.someMethod();
    this.__private__.m1.methodCall(this.someField1);
    this.someField2 = 'some value';
}

但是m1在这里不是真的。

But then m1 is not really private here.

还要注意,在那段代码中,m1只对返回的函数可见,如果theMethod是一个类的成员,该类的其他方法将不能看到m1(使它不同比Java上的private关键字)。也取决于你如何声明方法m1将是等价的静态(m1是一个对象的原型的函数,它是静态的,如果它不是一个原型,它不是静态的)。

Also note that in that piece of code m1 is only visible to the function returned, if theMethod was a member of a class the other methods of that class would not be able to see m1 (making it different than the "private" keyword on Java). Also depending on how you declared theMethod m1 would be the java equivalent to "static" (m1 is a function on the prototype of an object it's static, if it's not on a prototype it's not static).

这篇关于JavaScript:self-calling函数返回一个闭包。它是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆