javascript 之 第七章第三节(this关键字)

该章节将从以下几个方面来谈论ths的使用环境。

1/this和构造器

2/this和对象

3/this和函数

4/全局环境的this

5/this和DOM/事件

7/me/self/that/_this 暂存this

8/ES5 中新增的bind和 this

9/ES6箭头函数(arrow function)和 this

-- 1/ this和构造器
function Tab(nav,content)
{
this.nav=nav;
this.content=content;
}
Tab.prototype.getNav=function(){
return this.nav;
}
Tab.prototype.setNav=function(nav)
{
this.nav=nav;
}

--2/this 和 对象
JS中的对象对象不用类也可以创建
var Tab={
  nav:'',
content:'',
getNav:function(){
return this.nav;
},
setNav:function(n){
this.nav=n;
}
}

--3/this和函数
在 非严格模式 下,且this的值不是由该调用设置的,所以this的值默认指向全局对象
function f1(){
return this;
}
f1()==window; // true;在浏览器中,全局对象是window
f1()==global;// true;在Node中
在 严格模式 下,如果this没有被执行环境定义,那么将为undefined;
function f2(){
"use strict";//严格模式
return this;
}
f2()==undefined;//true
原因:因为f2是被直接调用的,不是作为对象的属性或方法调用

--4/全局环境的this
console.log(this==window); //true
a=37;
console.log(window.a);//37
this.b="mon";
console.log(window.b);//mon
console.log(b);//mon






原文地址:https://www.cnblogs.com/zmztya/p/10337957.html