如何制作一个javascript类方法的副本?

时间:2017-07-01 10:59:51

标签: javascript

我有一个javascript类

int

有关在javascript类中制作方法副本的最简单方法吗?

编辑:如果方法A和方法B是一些class A { methodA (){ //doing some operations with arguments } methodB (){ // i need to refer this function to `returns` function } // i am expecting something like below methodB : A.methods.methodA // NOT like below methodB (...args){ return this.methodA(...args); } } 方法,请提供一些解决方案。

1 个答案:

答案 0 :(得分:2)

你可以将它们复制到类之外,例如:

class A{
 returns(){
 }
 static returns(){
 }
}

A.sth=A.returns;
A.prototype.sth=A.prototype.returns;

你也可以在构造函数中绑定:

class A {
 constructor(){
  this.sth=this.returns.bind(this);
 }
 returns (){
//doing some operations with arguments
 }
}

(new A).sth()

或者您可以添加两个指向全局函数的指针(类语法尚不可能):

function returns(){
  return true;
}

function A(){}
A.prototype={
 returns:returns,
 sth:returns
};
//static:
Object.assign(A,{
 returns:returns,
 sth:returns
});

(new A).sth();
(new A).returns();
A.sth();
A.returns();