使用javscript'class'声明时如何设置'_this'或'self'

时间:2019-04-04 23:15:40

标签: javascript oop

使用“类”时如何设置“自我”?

我已经看到'self'变量可以使用'function'类声明在javascript类中设置为更可预测的'this'用法。我们如何使用“ class”声明来做到这一点?

函数VS类声明

// Using the 'function' declaration
function Apple (type) {
    var self = this
    self.type = type
    self.color = "red"
    self.getInfo = function() {
        return self.color + ' ' + self.type + ' apple'
    };
}

// Using the 'class' declaration
class Apple2 {
    constructor(type){
        var self = this
        self.type = type
        self.color = "red"
    }
    getInfo () {
        return self.color + ' ' + self.type + ' apple'
    }
}
let ap = new Apple('Granny')
let ap2 = new Apple2('Jazz')
console.log(ap.getInfo(), ap2.getInfo())
// prints 'red Granny apple undefined undefined apple'

编辑:

看起来好像在chrome控制台中的构造函数实际工作之前创建了'self'变量,但是webpack为此抛出了错误:

// Using the 'class' declaration
class Apple2 {
    self = this
    constructor(type){

        self.type = type
        self.color = "red"
    }
    getInfo () {
        return self.color + ' ' + self.type + ' apple'
    }
}
console.log(new Apple2('Jazz').getInfo())

1 个答案:

答案 0 :(得分:1)

使用类的正确方法是别名this

class Apple2 {
  constructor(type) {
    this.type = type
    this.color = 'red'
  }

  getInfo() {
    return `${this.color} ${this.type} apple`
  }
}

console.log(new Apple2('Jazz').getInfo())

原因是因为这实际上(大致)等同于以下代码:

function Apple(type) {
  this.type = type
  this.color = 'red'
}

Apple.prototype.getInfo = function() {
  return this.color + ' ' + this.type + ' apple'
}

console.log(new Apple('Granny').getInfo())

这就是使用this的原因。实际上,即使使用原始代码,也无需使用别名:

function Apple(type) {
  this.type = type
  this.color = 'red'
  this.getInfo = function() {
    return this.color + ' ' + this.type + ' apple'
  }
}

var apple = new Apple('Granny')

// does not make a difference
console.log(apple.getInfo())

var getInfo = apple.getInfo

// here is where it makes a difference
console.log(getInfo())
// how to fix
console.log(getInfo.call(apple))

有关此行为的更多信息,请参见How does the "this" keyword work?