您的位置:首页 > Web前端 > JavaScript

Some Essential JavaScript Questions And Answers(2)

2018-03-27 19:31 621 查看
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:

[译]:以上代码在控制台中的输入如下:
outer func:  this.foo = bar
outer func:  self.foo = bar
inner func:  this.foo = undefined
inner func:  self.foo = bar
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.
[译]:在外部函数中, 
this
 和
self
 两者都指向
myObject
,因此两者都可以正确地引用和访问 
foo
。在内部函数中, 
this
 不再指向 
myObject
。因此,
this.foo
 没有在内部函数中未定义,相反,将
this
引用到本地的变量
self
,即可保持在范围内,并且可以访问。 (附:在ES5之前,在内部函数中的
this
 将指向全局的 
window
 对象;反之,因为作为ES5,内部函数中的
this
 是未定义的)

Question4:

What is the significance of, and reason for, wrapping the entire content of a JavaScript source file in a function block?
[译]:封装一个JavaScript源文件的全部内容到一个函数块有什么意义,理由是什么?
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等等)。这种技术创建了一个围绕文件全部内容的闭包,也许更最重要的是,创建了一个私有的命名空间,从而有助于避免不同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:
[译]:这种技术的另一个特点是,允许一个易于引用的(可能更短的)别名用于全局变量。这通常用于,比如jQuery插件中。jQuery允许你使用jQuery.noConflict()来禁用 $ 对jQuery命名空间的引用。这样以后, 利用这种闭包技术,你的代码仍然可以使用$,如下所示:
(function($) { /* jQuery plugin code referencing $ */ } )(jQuery);
[非翻译]:这样说好像比较好理解一点
使用JQuery.noConflict()后,还可以恢复使用别名 $。创建并执行一个函数,在这个函数的作用域中仍然将 $ 作为 jQuery 的别名来使用即可。在这个函数中,原来的 $ 对象是无效的,这个函数对于大多数不依赖于其他库的插件都十分有效:
jQuery.noConflict();
(function($) {
$(function() {
// 使用 $ 作为 jQuery 别名的代码
});
})(jQuery);

... // 其他用 $ 作为别名的库的代码
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: