<!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>
// 函数的 this指向 普通函数指向window,
// 箭头函数指向其定义时的this指向window,构造函数指向实例对象,
// 事件所绑定的函数指向事件所绑定的对象
// 定时器的函数指向window
// 立即执行函数指向window
// 对象指向对象本身
// 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 (a, b) {
console.log(this);
return a + b;
}
}
console.log(o.add(1, 2));
// 构造函数的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>