function test1() {
console.log(this);
}
test1(); //window
function test2() {
'use strict';
console.log(this);
}
test2(); //严格模式,this为undefined
var obj1 = {
name: 'zhouy2',
sayName: function(){
setTimeout(function(){
console.dir(this);
console.log(this.name);
},1000);
}
}
obj1.sayName(); //this指向window,name为空字符串
var obj2 = {
name: 'zhouy2',
sayName: function(){
setTimeout(function(){
console.dir(this);
console.log(this.name);
}.bind(this),1000);
}
}
obj2.sayName(); //由于有bind,this指向调用者
var obj3 = {
name: 'zhouy2',
sayName: function() {
setTimeout(() => {
console.dir(this);
console.log(this.name);
},1000);
}
}
obj3.sayName(); //箭头函数,this继承自obj,指向的是定义它的对象obj,而不是window
window.val = 1;
var obj = {
val: 2,
dbl: function() {
console.dir(this)
val *= 2;
this.val *= 2;
console.log(val);
console.log(this.val);
}
}
//有前缀,this指向obj
obj.dbl(); //2 4
var func = obj.dbl;
//没有前缀,等价于window.func(),this指向window
func();
//多层嵌套箭头函数
var od1 = {
say: function() {
var f1 = () => {
console.log(this); //this指向obj
setTimeout(() => {
console.log(this); //this指向obj
},1000);
}
f1();
}
}
od1.say();
var od2 = {
say: function() {
var f1 = function() {
console.log(this); //this指向window
setTimeout(() => {
console.log(this); //this指向window
},1000);
}
f1();
}
}
od2.say();
var od3 = {
say: function() {
'use strict';
var f1 = function() {
console.log(this); //this指向window
setTimeout(() => {
console.log(this); //this指向window
},1000);
}
f1();
}
}
od3.say();
console.log(this);
}
test1(); //window
function test2() {
'use strict';
console.log(this);
}
test2(); //严格模式,this为undefined
var obj1 = {
name: 'zhouy2',
sayName: function(){
setTimeout(function(){
console.dir(this);
console.log(this.name);
},1000);
}
}
obj1.sayName(); //this指向window,name为空字符串
var obj2 = {
name: 'zhouy2',
sayName: function(){
setTimeout(function(){
console.dir(this);
console.log(this.name);
}.bind(this),1000);
}
}
obj2.sayName(); //由于有bind,this指向调用者
var obj3 = {
name: 'zhouy2',
sayName: function() {
setTimeout(() => {
console.dir(this);
console.log(this.name);
},1000);
}
}
obj3.sayName(); //箭头函数,this继承自obj,指向的是定义它的对象obj,而不是window
window.val = 1;
var obj = {
val: 2,
dbl: function() {
console.dir(this)
val *= 2;
this.val *= 2;
console.log(val);
console.log(this.val);
}
}
//有前缀,this指向obj
obj.dbl(); //2 4
var func = obj.dbl;
//没有前缀,等价于window.func(),this指向window
func();
//多层嵌套箭头函数
var od1 = {
say: function() {
var f1 = () => {
console.log(this); //this指向obj
setTimeout(() => {
console.log(this); //this指向obj
},1000);
}
f1();
}
}
od1.say();
var od2 = {
say: function() {
var f1 = function() {
console.log(this); //this指向window
setTimeout(() => {
console.log(this); //this指向window
},1000);
}
f1();
}
}
od2.say();
var od3 = {
say: function() {
'use strict';
var f1 = function() {
console.log(this); //this指向window
setTimeout(() => {
console.log(this); //this指向window
},1000);
}
f1();
}
}
od3.say();