[英]What was the rationale behind having the receiver in functions default to the global object?
在JavaScript的早期版本中,将receiver
(也称为context
)默认为全局对象的原因是什么?
function a() {
console.log(this); // window
}
Brendan Eich 回答道 :
因此,顶级函数(第一个版本中唯一的函数)可以充当窗口或框架(后来的iframe)方法。 仍在使用。
JS术语:“接收器”是影响JS的语言中的标准OO术语,而不是高度重载的“上下文”。
问题提交给Brendan Eich:
所以ES1没有方法? (参见你对顶级fns的评论)
Brendan Eich:
不,JS9在'95(之后没有“ES”)通过函数值属性获得方法,但所有函数都是顶级的。 ES1标准化。
'99中的ES3添加了函数表达式和嵌套函数(闭包),我在那10天没有时间实现。
要回到orig q:在窗口w中,函数m(){}使wm()可以使用
this
== w从其他可到达的窗口/帧中调用。
因此,顶层函数可以作为裸函数(即不作为方法)从与其相同“顶部”窗口相关联的其他窗口和框架中轻易调用。
例如,如果页面包含两个框架,每个框架定义其自己的函数foo
,该函数记录全局对象的属性。 像这样:
index.html的:
<html>
<title>index.html</title>
<frameset cols="30%,70%">
<frame name="Frame1" src="frame1.html">
<frame name="Frame2" src="frame2.html">
</frameset>
frame1.html
<html>
<title>frame1.html</title>
<script>
function foo() {
console.log('frame1::foo: ', this.id);
}
this.id = 'window object one!';
</script>
frame2.html
<html>
<title>frame2.html</title>
<script>
function foo() {
console.log('frame2::foo: ', this.id);
}
this.id = 'window object two!';
</script>
如果我们现在从index.html运行以下命令:
var foo1, foo2;
foo1 = window.top.Frame1.foo;
foo2 = window.top.Frame2.foo;
foo1(); // "window object one!"
foo2(); // "window object two!"
因此,我们可以看到接收器默认为函数上下文的全局对象。
另一种实现方式是将裸函数的接收器默认为未定义,但AFAICT在JavaScript的早期被认为是“不太方便”。 记住JS最初是在考虑非专业开发人员的情况下开发的。
当我们问这个问题变得更有趣时,为什么这种行为扩展到嵌套函数和函数表达式(在ES3中标准化,但事先实现)? 基于阅读Brendan Eich的回答,我的猜测是,在嵌套函数和函数表达式开发时,这根本不是公认的问题,因此使用了基于顶级函数的现有行为。
该问题仅在ES5中得到正式认可,并具有"use strict"
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.