目录
普通函数中
<script>
function function1(){
var a = 'apple';
console.log("函数调用模式"+a);//a的值
console.log(this);//window
console.log(this.a);//undefined
}
function1();
</script>
对象的方法中
属性外对象外部
//对象的方法调用模式
var b = {
name:'banana',
sayName:function(){
console.log("对象的方法调用模式"+this.name);//结果为banana,this代表b可获取到name
console.log(this);//对象(object)
}
}
b.sayName();
结果为banana,this代表b可获取到name。
属性在对象内部
var c = {
name:'firstName',
d:{
name:'secondName',
fn:function(){
console.log("对象的方法调用2"+this.name);//获取到seconName,this即指d这个对象
console.log(this);//对象(object)
}
}
}
c.d.fn();
获取到seconName,this即指d这个对象。
构造函数中
//构造函数的调用模式
function e(){
console.log("构造函数的调用模式"+this);
}
var f = new e();
//构造函数的调用模式2
function g(){
this.name = 'orange';
}
var h = new g();
console.log(h.name);
对象h自动获取到了构造方法g()中的属性,this代表g()中的对象
绑定事件函数中
yellowStar.onclick = function (event) {
console.log("星星执行了");
if (this.getAttribute("src") == './images/star.png') {
this.setAttribute('src', './images/stary.png');
} else {
// console.log("11");
this.setAttribute('src', './images/star.png');
}
}
此例子为一个鼠标点击事件,通过点击获取到的星星DOM,改变其src值从而实现点击之后变换星星, this即为yellowStar.
定时器中
window.setTimeout(function() {
console.log('定时器的this:' + this);
}, 1000);
指向的是window
立即执行函数
(function() {
console.log('立即执行函数的this' + this);
})();
指向的仍然为window。