<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>函数的this</title>
</head>
<body>
<button>
点击
</button>
<script>
// var f = new Function("a", "b", 'console.log(a+b);');
// f(1,2)
// 普通函数的this指向window
function add(a, b) {
console.log(this);
return a + b;
}
console.log(add(1, 2));
// 对象的函数指向的是对象本身
var o = {
name: "张三",
add: function () {
return function(){
// 这里的this指向的是window对象,而是函数的本身,需要注意一下
console.log(this)
}
}
}
o.fun()()
// 构造函数的this指向新创建的对象
function Star(age) {
this.age = age;
this.uname='张三'
console.log(this);
}
var s1 = new Star(20);
console.log(Star.prototype==s1.__proto__);
console.log(s1.__proto__);
// 事件绑定的this指向的是函数的调用者
var btn = document.querySelector("button");
btn.onclick = function () {
console.log(this);
}
// 定时器的this指向window
setTimeout(function () {
console.log('定时器中的',this);
}, 1000);
//立即执行函数的this指向window
(function () {
console.log('立即执行函数中的',this);
})();
</script>
</body>
</html>