javaScript中this以及window对象和window对象的name属性

一打开页面,即第1次运行,运行结果如下:

第2次运行,运行结果如下:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>javaScript中this以及window对象和window对象的name属性</title>
<script type="text/javascript">
//打开浏览器,执行本页面所有的代码,第一次执行和第二次执行,运行结果会不同,大家可以试一下

//全局变量(全局变量是属于window对象的属性)
var hometown = "江西省赣州市于都县渡江大道666666号";
console.log(window.hometown, hometown);//window可以省略不写

var salary = 19800.56;
//19800.56 19800.56 19800.56
console.log(salary, window['salary'], window.salary);
//window['salary']这样写才对,如下这种写法不可以
console.log(window[salary]);//undefined

console.log(window, this);
console.log(window == this, window === this); //true true

function Dog(str) {
	this.name = str;
}

var dog1 = new Dog('旺财');
console.log(dog1.name); //结果  
console.log(name); //结果

//在js中window对象有name属性,name属性的值默认是""空字符
console.log(window.name);
console.log(name); //window可以省略不写

function fn(str) {
	console.log("hello" + str, this);
	this.name = str;
	this.age = 26;
}
//如果把下面这2行代码注释掉,运行效果会大不相同,大家可以试一试,会学习到一些意想不到的知识
window.fn("令狐冲");
fn("韦小宝");

var f = new fn("张无忌");

console.log(f.name, f.age);
console.log(name);
console.log(name, age);
console.log(window.name, window.age);

function Person(str) {
	this.userName = str;
	this.userAge = 12;
}

var p1 = new Person('杨过');
console.log(p1.userName); //杨过
// console.log(userName); //Uncaught ReferenceError: userName is not defined

console.log(p1.userAge); //12
// console.log(userAge); //Uncaught ReferenceError: userAge is not defined
window.Person("段誉");
console.log(userName, window.userName); //段誉 段誉
console.log(userAge, window.userAge); //12 12

Person("乔峰");
console.log(userName, window.userName); //乔峰 乔峰
console.log(userAge, window.userAge); //12 12

console.log(window.name);

function Cat(str) {
	this.name = str;
	//没有使用var关键字定义的变量是全局变量
	hobby = "羽毛球"; //全局变量(全局变量是属于window对象的属性)
}

var catA = new Cat('Tom');
console.log(catA.name);//Tom
console.log(name);

console.log(catA.hobby);//undefined
console.log(hobby, window.hobby);//羽毛球 羽毛球
</script>
</head>
<body style="background-color: #CCE8CF;">
<h2>javaScript中this以及window对象和window对象的name属性</h2>
<div id="div1" style="background-color: Wheat; height: 200px;">
</div>
</body>
</html>

javaScript中this以及window对象和window对象的name属性的知识点,大家最好是自己去写一写,测一测,自己去理解一下。

猜你喜欢

转载自blog.csdn.net/czh500/article/details/114994833
今日推荐