Nat*_*ael 7 javascript methods prototype class ecmascript-5
我需要使用新语法向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.
Run Code Online (Sandbox Code Playgroud)
它只是打印:
class X{
constructor() {
this.a = 'b'
}
x(){}
}
Run Code Online (Sandbox Code Playgroud)
但我期待
class X{
constructor() {
this.a = 'b'
}
x(){}
y(){
console.log('y');
}
}
Run Code Online (Sandbox Code Playgroud)
我怎样才能在Javascript类中添加新方法?
这工作正常,如果您在 google chrome 控制台中检查这个,那么请通过扩展proto节点来检查。或者尝试检查
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())
Run Code Online (Sandbox Code Playgroud)
下面是使用原型从类范围之外创建方法的示例:
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())
Run Code Online (Sandbox Code Playgroud)
需要注意的一个非常重要的事情是,使用原型向类添加方法不会改变类的结构。因此记录对象不会呈现该方法。但该方法可用于该类的所有子类和实例。