如何在 Javascript ES6 中向 class 添加方法

How to add an method to a class in Javascript ES6

我需要使用新语法向 Javascript class 添加一个方法。我这样试过:

class X{

    constructor() {
        this.a = 'b'
    }

    x(){

    }
}

X.prototype.y = function (){
    console.log('y')
}

var x = new X()

x.y()

console.log(X) // print the  the class but not the new method.

它只是打印:

class X{

    constructor() {
        this.a = 'b'
    }

    x(){}
}

但我预料到了

class X{

        constructor() {
            this.a = 'b'
        }

        x(){}

        y(){
            console.log('y');
        }
    }

如何向 Javascript class 添加新方法?

这工作正常,如果您在 google chrome 控制台中检查它,请通过展开 proto 节点进行检查。 或者尝试检查 console.log(X.y)console.log(X.prototype.y)console.log(x.y) 这必须打印那个函数

我知道有点晚了,但这能解决你当时的问题吗?

class XWithY extends X {
  constructor() {
    super()
  }
  y() {
    console.log('y')
  }
}

const xwy = new XWithY();

console.log(xwy instanceof X); // outputs true

添加方法到class主要有两种方法,这可以在编写代码时在class的范围内或使用“.prototype”将方法附加到您的class。 下面是在 class 范围内添加方法的示例:

class Person {
   constructor(fName, lName) {
      this.firstName = fName;
      this.lastName = lName;
   }
   sayName = function() {
   return `My Name is ${this.firstName} ${this.lastName}`
   }
}
const firstPerson= new Person ("Thor", "Odinson")
console.log(firstPerson.sayName())

下面是使用原型从 class 范围之外创建方法的示例:

class Person {
   constructor(fName, lName) {
      this.firstName = fName;
      this.lastName = lName;
   }
}
Person.prototype.sayName = function() {
   return `My Name is ${this.firstName} ${this.lastName}`
}
const secondPerson= new Person ("Tony", "Stark")
console.log(secondPerson.sayName())

需要注意的一个非常重要的事情是,使用原型向 class 添加方法不会更改 class 的结构。所以记录对象不会呈现方法。但该方法适用于所有子classes 和 class.

的实例