Skip to content

this关键字 #7

Open
Open

Description

@Yangxiaqing

我们在JS中主要研究的都是函数中的this
JS中的this代表的是当前行为执行的主体;JS中的context代表的是当前行为执行的环境(区域);
this是谁和函数在哪定义的和在哪执行的都没有任何的关系;

如何的区分this呢?(5)

  • 函数执行,首先看函数名之前是否有".",有的话,"."前面是谁this就是谁;没有的话this就是window
function fn(){
	console.log(this);
}
var obj = {fn: fn};
fn(); // this---->window
obj.fn(); // this---->obj
function sum() {
	// this--->window
	fn(); //this--->window
}
sum();
var oo = {
	sum:function() {
		// this---->oo
		fn(); // this--->window
	}
};
oo.sum();
  • 自执行函数中的this永远是window
  • 给元素的每一个事件绑定方法,当事件触发的时候,执行对应的方法,方法中的this就是当前的元素
<body>
<div id="div1">点我</div>
<script>
function fn(){
	console.log(this);
}
var obj = {fn: fn};
fn(); // this---->window
obj.fn(); // this---->obj
document.getElementById('div1').onclick = fn; // fn中的this是#div1
document.getElementById('div1').onclick = function () {
	// this --->#div1
	fn(); //fn中的this是window
};
</script>
</body>

360面试题:

var num = 20;
var obj = {
	num: 30,
	fn: (function (num) {
		this.num *= 3;//window.num*=3,window下的num=60 
		num += 15;// num=35
		var num = 45; //num=45
		return function () {
			this.num *= 4;//window.num*=4,window下的num=240;
			num += 20;
			console.log(num);
		}
	}) (num) // 把全局变量num的值20赋值给了自执行函数的形参,而不是obj下的30,如果想是obj下的3,我们需要写obj.num
};
var fn = obj.fn;
fn ();// 65
obj.fn();// 85
console.log(window.num, obj.num);//240 120

image

Activity

  1. added a commit that references this issue on Mar 5, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions