当前位置: 移动技术网 > IT编程>开发语言>JavaScript > Javascript全局对象功能

Javascript全局对象功能

2019年03月23日  | 移动技术网IT编程  | 我要评论

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对象可以嵌入到其他的<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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网