Javascript学习---全局对象

Javascript在被创建的时候就已经有了全局对象这个概念,在浏览器里,全局对象默认是“window”,在Node.js里面叫做“global”


全局对象

Javascript的全局对象主要有以下两个功能:

(1)提供对内置函数和值的访问,例如我们直接调用alert()或者使用window.alert()

alert("Hello");

// the same as
window.alert("Hello");

这对于其他全局对象也是一样的,例如使用window.Array来取代Array


(2)提供对全局函数和全局var变量的访问,例如:

var phrase = "Hello";

function sayHi() {
  alert(phrase);
}

// can read from window
alert( window.phrase ); // Hello (global var)
alert( window.sayHi ); // function (global function declaration)

// can write to window (creates a new global variable)
window.test = 5;

alert(test); // 5

但是,全局变量不能使用let/const来修饰,否者使用window对象来调用时显示undefined,例如:

let user = "John";
alert(user); // John

alert(window.user); // undefined, don't have let
alert("user" in window); // false

“window”对象的使用

在浏览器中,一般我们很少直接使用window对象,但在一些特定的情况下就需要使用到window对象:

(1)明确指定全局变量或者局部变量

var user = "Global";

function sayHi() {
  var user = "Local";

  alert(window.user); // Global
}

sayHi();

(2)检测内置内置变量或者内置函数是否存在

if (window.XMLHttpRequest) {
  alert('XMLHttpRequest exists!')
}
由于XMLHttpRequest属于window对象里的属性,所以我们必须使用window对象来调用,如果是if(XMLHttpRequest)则会报错


(3)从特定的window中获取变量

我们知道浏览器可以有多个窗口和标签页,因此window对象可以嵌入到其他的<iframe>中,例如:

<iframe src="/" id="iframe"></iframe>

<script>
  alert( innerWidth ); // get innerWidth property of the current window (browser only)
  alert( Array ); // get Array of the current window (javascript core builtin)

  // when the iframe loads...
  iframe.onload = function() {
    // get width of the iframe window
    alert( iframe.contentWindow.innerWidth );
    // get the builtin Array from the iframe window
    alert( iframe.contentWindow.Array );
  };
</script>

这里,前面两个alert()是来自当前窗口的window对象,而最后两个alert()是来自ifram窗口中的window对象


this和全局对象

在浏览器中,全局代码区的this指向的对象是window,例如:

// outside of functions
alert( this === window ); // true

在non-strict模式下直接调用函数的话,函数内部的this是指向window对象的,例如:

// not in strict mode (!)
function f() {
  alert(this); // [object Window]
}

f(); // called without an object



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值