js的上下文

本文探讨了JavaScript中的上下文this,包括在对象声明、函数声明和构造函数声明中的不同指向。此外,还详细介绍了call和apply方法的使用,包括半替换和全替换的场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一,js中的上下文this

1,指向函数拥有者
2,只能在函数内部使用

二,各种场景使用

1,对象声明(this指向对象)
var pet = {
    words: '...',
    speak: function() {
        console.log(this.words)
        console.log(this === pet)
    }
}

pet.speak()

执行结果

...
true
2,函数声明(this指向global(或window))
function pet(words){
    this.words = words

    console.log(this.words)
    console.log(this === global)
}

pet('...') 

执行结果

...
true
3,构造函数声明(this指向新声明的对象)
function Pet(words) {
    this.words = words
    this.speak = function() {
        console.log(this.words)
        console.log(this)
    }
}

var cat = new Pet('Miao')

cat.speak()

执行结果

Miao
Pet { words: 'Miao', speak: [Func]}

三,call和apply

1,半替换
var pet = {
    words: '...',
    speak: function(say) {
        console.log(say + ' ' + this.words)
    }
}

// pet.speak('Speak')

var dog = {
    words: 'Wang'
}
pet.speak.call(dog, 'Speak')

//call把this由pet指向了dog,所以

//执行结果
//Speak Wang
2,全替换
function Pet(words) {
    this.words = words
    this.speak = function() {
        console.log(this.words)
    }
}

function Dog(words) {
    Pet.call(this, words)
    // Pet.apply(this, arguments)
}

var dog = new Dog('Wang')

dog.speak()

//this由Pet指向Dog,相当于构造函数整个继承。

//执行结果
//Wang
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值