javascript
Some Essential JavaScript Questions And Answers(2)
Some Essential JavaScript Questions And Answers
Question3:
What will the code below output to the console and why?
[譯]:以下代碼在控制臺的輸出是?為什么?
var myObject = {foo: "bar",func: function() {var self = this;console.log("outer func: this.foo = " + this.foo);console.log("outer func: self.foo = " + self.foo);(function() {console.log("inner func: this.foo = " + this.foo);console.log("inner func: self.foo = " + self.foo);}());} }; myObject.func();Answer:
The above code will output the following to the console:
[譯]:以上代碼在控制臺中的輸入如下:
In the outer function, both this and self refer to myObject and therefore both can properly reference and access foo.
In the inner function, though, this no longer refers to myObject. As a result, this.foo is undefined in the inner function, whereas the reference to the local variable self remains in scope and is accessible there.
[譯]:在外部函數(shù)中,?this?和self?兩者都指向 myObject,因此兩者都可以正確地引用和訪問?foo。在內(nèi)部函數(shù)中,?this?不再指向?myObject。因此,this.foo?沒有在內(nèi)部函數(shù)中未定義,相反,將this 引用到本地的變量self ,即可保持在范圍內(nèi),并且可以訪問。 (附:在ES5之前,在內(nèi)部函數(shù)中的this?將指向全局的?window?對象;反之,因為作為ES5,內(nèi)部函數(shù)中的this?是未定義的)
Question4:
What is the significance of, and reason for, wrapping the entire content of a JavaScript source file in a function block?
[譯]:封裝一個JavaScript源文件的全部內(nèi)容到一個函數(shù)塊有什么意義,理由是什么?
Answer:
This is an increasingly common practice, employed by many popular JavaScript libraries (jQuery, Node.js, etc.). This technique creates a closure around the entire contents of the file which, perhaps most importantly, creates a private namespace and thereby helps avoid potential name clashes between different JavaScript modules and libraries.
[譯]:這是一個越來越普遍的做法,被許多流行的JavaScript庫采用(jQuery,Node.js等等)。這種技術(shù)創(chuàng)建了一個圍繞文件全部內(nèi)容的閉包,也許更最重要的是,創(chuàng)建了一個私有的命名空間,從而有助于避免不同JavaScript模塊和庫之間潛在的名稱沖突。
Another feature of this technique is to allow for an easily referenceable (presumably shorter) alias for a global variable. This is often used, for example, in jQuery plugins. jQuery allows you to disable the $ reference to the jQuery namespace, using jQuery.noConflict(). If this has been done, your code can still use $ employing this closure technique, as follows:
[譯]:這種技術(shù)的另一個特點是,允許一個易于引用的(可能更短的)別名用于全局變量。這通常用于,比如jQuery插件中。jQuery允許你使用jQuery.noConflict()來禁用 $ 對jQuery命名空間的引用。這樣以后, 利用這種閉包技術(shù),你的代碼仍然可以使用$,如下所示:
[非翻譯]:這樣說好像比較好理解一點
使用JQuery.noConflict()后,還可以恢復(fù)使用別名 $。創(chuàng)建并執(zhí)行一個函數(shù),在這個函數(shù)的作用域中仍然將 $ 作為 jQuery 的別名來使用即可。在這個函數(shù)中,原來的 $ 對象是無效的,這個函數(shù)對于大多數(shù)不依賴于其他庫的插件都十分有效:
總結(jié)
以上是生活随笔為你收集整理的Some Essential JavaScript Questions And Answers(2)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 让人心动的情话的句子143个
- 下一篇: Some Essential JavaS