this的指向()-其他
this的指向()
<body>
<button>123</button>
<script>
// "use strict";开启严格模式普通函数指向 undefined
function fn() {
console.log(this); //普通函数this指向window
}
fn();
let fun = function () {
console.log(this); //匿名函数中的this指向window
};
fun();
setInterval(function () {
// console.log(this);//定时器中的this指向window
}, 1000);
const btn = document.querySelector("button");
btn.addEventListener("click", function () {
console.log(this); //事件处理函数this指向触发当前事件的事件源<button>123</button>
});
let obj = {
name: "zs",
age: 17,
sing() {
console.log("闹闹 哄哄");
console.log(this); //{name: 'zs', age: 17, sing: }对象中的this指向当前对象
},
};
obj.sing();
// =====================
function Star(name, age) {
(this.name = name), (this.age = age);
console.log(this); //{name: 'hh', age: 17} 构造函数中的this指向实例化对象
}
const zjl = new Star("hh", 17);
Star.prototype.sing = function () {
console.log(this); //{name: 'hh', age: 17} 构造函数原型方法的调用this也指向实例化对象
};
zjl.sing();
//=======================
const obj1 = {
uname: "zs",
sing: () => {
console.log(this); //指向windod(箭头函数中没有this指向 和他当前所处环境的外层作用域中的this指向一致)
},
};
obj1.sing();
</script>
</body>
————————
<body>
<button>123</button>
<script>
// "use strict";开启严格模式普通函数指向 undefined
function fn() {
console.log(this); //普通函数this指向window
}
fn();
let fun = function () {
console.log(this); //匿名函数中的this指向window
};
fun();
setInterval(function () {
// console.log(this);//定时器中的this指向window
}, 1000);
const btn = document.querySelector("button");
btn.addEventListener("click", function () {
console.log(this); //事件处理函数this指向触发当前事件的事件源<button>123</button>
});
let obj = {
name: "zs",
age: 17,
sing() {
console.log("闹闹 哄哄");
console.log(this); //{name: 'zs', age: 17, sing: }对象中的this指向当前对象
},
};
obj.sing();
// =====================
function Star(name, age) {
(this.name = name), (this.age = age);
console.log(this); //{name: 'hh', age: 17} 构造函数中的this指向实例化对象
}
const zjl = new Star("hh", 17);
Star.prototype.sing = function () {
console.log(this); //{name: 'hh', age: 17} 构造函数原型方法的调用this也指向实例化对象
};
zjl.sing();
//=======================
const obj1 = {
uname: "zs",
sing: () => {
console.log(this); //指向windod(箭头函数中没有this指向 和他当前所处环境的外层作用域中的this指向一致)
},
};
obj1.sing();
</script>
</body>