js中箭头函数在对象内部的继承
文章目录
function函数
function Person(){
this.name = 'Jack',
this.age = 25,
this.sayName = function(){
console.log(this.name)
function inner(){
console.log(this.name)
console.log(this)
}
inner()
}
}
let x = new Person()
x.sayName()Output

在这里, this.sayName() 中的 this.name 是可访问的,因为 this.sayName() 是一个对象的方法。
但是,inner() 是一个普通函数, this.name 不可访问,因为 this 指的是全局对象(浏览器中的 Window 对象)。 因此,inner() 函数中的 this.name 给出了 undefined。
箭头函数
function Person() {
this.name = 'Jack',
this.age = 25,
this.sayName = function () {
console.log(this.age);
let innerFunc = () => {
console.log(this.age);
}
innerFunc();
}
}
const x = new Person();
x.sayName();Output

这里,innerFunc() 函数是使用箭头函数定义的。 在箭头函数内部, this 指的是父级的作用域。 因此, this.age 给出 25。

评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册⭐️ Admin快速开发: https://show.cool-admin.com/
赞 0⭐️ 官方文档: https://cool-js.com
赞 0⭐️ chatgpt在线体验: https://cool-js.com/ai/chat-vip/index.html?r=helloworld
赞 0