js this_练习

  1. 函数预编译后 this = window
  2. 全局的 this = window
  3. function.call(obj) / function.apply(obj) : this = obj
  4. obj.function(); 函数体里面的 this = obj
function a() {return this}
var b = a();
var c = new a();
var d = this;
var e = a.call({name : 'chl'});
var f = {
	fAttr : function () {
		return this
	}
}

// 	b = {parent: Window, opener: null, …}	// = window
// 	c = a {		// = a.prototype
// 		__proto__ : {
// 			constructor : a,
// 			__proto__ : {...}
// 		}
// 	}
//	d = {parent: Window, opener: null, …}	// = window
//	e = {
//		name : 'chl',
//		__proto__ : {...}
//	}
//	f.fAttr() = {	// = f
//		fAttr : ƒ (),		// = function () {return this}
//		__proto__ : {...}
//	}

  • 练习
var name = '222';
var a = {
	name : '111',
	say : function () {
		console.log(this.name);
	}
}
var fun = a.say;	// = function () {console.log(this.name);}
fun();		// this = window	// window.name = '222'
a.say();	// this = a			// a.name = '111'

var b = {
	name : '333',
	say : function (fun) {
		fun();
	}
}
b.say(a.say);
//	b.say = function (fun) {	// fun = function () {console.log(this.name);}
//		this = b
//		fun();		// this = window	// window.name = '222'
//	}
b.say = a.say;		// b.say = function () {console.log(this.name);}
b.say();	// this = b		// b.name = '333'

// console.log 输出:
// 222
// 111
// 222
// 333
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值