如何在 Javascript ES6 中向类添加方法
How to add an method to a class in Javascript ES6
我需要使用新语法向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
相关文章:
- 在对象中添加方法时出现问题
- 什么意思是“;向原型添加方法”;
- jQuery验证器添加方法未定义
- 向通过ReST JSON调用生成的Angular Javascript对象添加方法
- 向React中的高阶组件添加方法
- 向JavaScript对象添加方法
- 如何向[]添加方法
- 如何在流星js中为对象添加方法
- jQuery.validation 在生日年龄验证中添加方法错误
- 使用 IE8 添加方法的 JavaScript 错误
- 向方法添加方法
- 如何在 Javascript ES6 中向类添加方法
- Javascript:向对象类添加方法的优缺点是什么
- 如何更改“动物”的原型并添加方法“sayName”来打印语句
- 如何在 Illustrator CS5.1+ 中创建画板对象的添加方法所需的矩形对象
- 如何在 nodejs 中全局添加方法到 JSON、Date 或其他“本机”对象
- 什么类/类型是未定义的,是否可以向其扩展/添加方法
- 为什么在 javascript 中向数组原型添加方法会破坏 for 循环上的迭代
- 向对象添加方法
- 动态添加方法到对象