javascript this key world understand

这个例子能更好的理解this代表的是运行时,动态代理的对象。

function ask(question) {
    console.log(this.teacher,question);
}

function otherClass() {
   let myContext = {
       teacher: "Suzy3"
   } 
   ask.call(myContext,"why?")
}

otherClass();

第二个理解,使用prototype来理解this

function Workshop(teacher) {
    this.teacher = teacher;
}
// 在这里不能使用箭头函数,因为箭头函数中的this会默认绑定outscoper的this
/**
Workshop.prototype.ask = question =>{
    console.log(this);  // 箭头函数中,this绑定的是Window
    console.log(this.teacher,question);
}
*/

Workshop.prototype.ask = function(question){
    console.log(this); 
    console.log(this.teacher,question);
}

var kyle = new Workshop("kyle");
kyle.ask("Please answer the question");
// kyle Please answer the question

对象中的this

定义一个简单的对象

let user = {
    name: 'Q10Viking',
    city: 'BeiJing',
    code: function () {
        console.log(`${this.name} is learning javascript at ${this.city}`)
    }
}

console.log(user.code());

其中需要注意,在对象中定义方法不能使用箭头函数,因为箭头函数没有单独的this,它只会默认的从上一级继承this,MDN Javascript Arrow functions,但是可以简化为这样。

let user = {
    name: 'Q10Viking',
    city: 'BeiJing',
    code() {
        console.log(`${this.name} is learning javascript at ${this.city}`)
    }
}

Class 中的this

class Workshop{
    constructor(teacher){
        this.teacher = teacher;
    }
    ask(question){
        console.log(this); 
        console.log(this.teacher,question);
    }
}

var kyle = new Workshop("kyle");
kyle.ask("Please answer the question");
// kyle Please answer the question
发布了121 篇原创文章 · 获赞 3 · 访问量 4169

猜你喜欢

转载自blog.csdn.net/Q10CAU/article/details/104959285