this的指向问题

阅读 55

2022-02-28

// 直接调用
function fn1() {
    console.log(this);
}

fn1(); // 指向的是window

// 使用对象调用
let fn2 = {
    name: '张三',
    getName: function () {
        console.log(this.name);
    }
}

fn2.getName(); // 张三

// 使用原型调用
function fn3(name) {
    this.name = name;
}

fn3.prototype.getUserName = function () {
    console.log(this.name);
}

let fn4 = new fn3("张三");
fn4.getUserName(); // 张三
// 箭头函数指向的是外部也就是window

精彩评论(0)

0 0 举报