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

How to add an method to a class in Javascript ES6

本文关键字:添加 方法 ES6 Javascript      更新时间:2023-09-26

我需要使用新语法向Javascript类添加一个方法。我尝试了这种方式:

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 类添加新方法?

工作正常,如果您在谷歌浏览器控制台中检查这一点,那么请通过展开原型节点进行检查。或者尝试检查 console.log(X.y)console.log(X.prototype.y)console.log(x.y)这必须打印该函数

有两种

主要方法可以将方法添加到类中,这可以在编写代码或使用".prototype"将方法附加到类时在类的范围内。下面是在类范围内添加方法的示例:

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 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())

需要注意的非常重要的一点是,使用 prototype 向类添加方法不会更改类的结构。因此,记录对象不会呈现该方法。但是该方法可用于该类的所有子类和实例。

您可以使用

Object.setPrototypeOf。

例:

// A class…
class Someone {
  constructor(qui){
    this.qui = qui
  } 
}
// A mixins with new methods
class MyMixins {
  says(quoi){
    console.log(this.qui + " says "+ quoi)
  }
  eats(quoi){
    console.log(this.qui + " eats "+quoi)
  }
}
// An instance…
const marion = new Someone("Marion")
// This fails…
//marion.says("hello!")
//marion.eats("potatoes")
//-----> Here's the trick <------
Object.setPrototypeOf(Someone.prototype, MyMixins.prototype);
// This pass…
marion.says("hello!")   //=> "Marion says hello!"
marion.eats("potatoes") //=> "Marion eats potatoes"
我知道

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

class XWithY extends X {
  constructor() {
    super()
  }
  y() {
    console.log('y')
  }
}
const xwy = new XWithY();
console.log(xwy instanceof X); // outputs true