前端this相关
前端this相关:
<script>
//示例一
function func1() {
console.log(this); //this代指window
}
func1();
//window.func1();
//示例二
function Func() {
this.name = "jia"; //this代指obj
}
var obj = new Func();
console.log(obj.name); //jia
//示例三
function Func2() {
this.name = "kaylee";
this.show = function () {
console.log(this); //this代指obj2
}
}
var obj2 = new Func2();
obj2.show();
//示例四
var userInfo = {
name: "jia",
age: 18,
show: function () {
console.log(this); //this代指userInfo
}
};
userInfo.show();
//示例五
var userInfo2 = {
name: "kaylee",
age: 18,
show: function () {
console.log(this); //this代指userInfo2
(function () {
console.log(this); //this代指window
})()
}
};
userInfo2.show();
//示例五可以写作:
var userInfo3 = {
name: "kaylee",
age: 18,
show: function () {
console.log(this); //this代指userInfo3
inner();
}
};
userInfo3.show();
function inner() {
console.log(this); //this代指window
}
//示例六
var userInfo4={
name:"kaylee",
age:18,
show:function () {
console.log(this); //this代指userInfo4
var that = this;
(function () {
console.log(that); //that代指userInfo4
})()
}
};
userInfo4.show();
</script>
总结:
函数被 对象.函数 执行,那么函数中的this就是该对象

浙公网安备 33010602011771号