JS /将类方法导入另一个类

时间:2019-06-12 01:14:05

标签: javascript class es6-class

是否可以在JS中将方法从一个类导入另一个类?

说我有一堂课A

class A {
    someMethod(parameters){
        // some code here
    }
}

并且我希望能够在另一个类B中对该方法使用别名,即

aInstance = new A();
class B {
    anotherMethod = aInstance.someMethod;

}

我知道这行不通,但这是语法问题,还是无法在这样的类对象之间传递方法?

3 个答案:

答案 0 :(得分:0)

使用实例:

anotherMethod = aInstance.someMethod;

代替

anotherMethod = A.someMethod;

答案 1 :(得分:0)

您尝试执行的操作不是无效的语法,尽管这不是正确的方法。

第一件事你可能是故意的

this

从技术上讲是可行的,但这不是最好的方法,因为在函数内部使用this时可能会遇到问题。

要防止出现class A { someMethod = (parameters) => { //... some code } } class B { anotherMethod = new A().someMethod; } 问题,可以使用箭头功能

// A.js
export const someMethod = (parameters) => {

}

// B.js
import {someMethod} from './A';

class B extends A {
  anotherMethod = someMethod;
}

解决此问题的另一种方法,具体取决于您要实现的是导出函数而不是将其作为类成员。

class A {
  someMethod = (parameters) => {
    //... some code
  }
}

class B extends A {
  anotherMethod = (...parameters) => {
    super.someMethod.apply(this, parameters);
  }
}

最后,根据两个类之间的关系要考虑的另一件事是,使用继承是否明智

someMethod

通过这种方式,仍然可以在B的实例上调用reverse

答案 2 :(得分:0)

另一种方法是在类<?php $host = "localhost"; $dbusername = "asta"; $dbpassword = "*******"; $dbname = "asta"; // Create connection $conn = new mysqli ($host, $dbusername, $dbpassword, $dbname); if (mysqli_connect_error()){ die('Connect Error ('. mysqli_connect_errno() .') ' . mysqli_connect_error()); } else{ $userid = filter_input(INPUT_POST, 'userid'); $reason = filter_input(INPUT_POST, 'reason'); $duration = filter_input(INPUT_POST, 'duration'); $sql = "SELECT `user_id` FROM `punishments` WHERE `user_id`='$userid'"; $result = $conn->query($sql); if($result->num_rows >= 1) { echo "The user with userid '$userid' is already banned."; } else { $sql = "INSERT INTO punishments (user_id, reason, duration, origin_id, type, time, active) values ('$userid','$reason','$duration','10','2','1','1')"; if ($conn->query($sql)){ echo "The user with userid '$userid' has been banned!"; } else{ echo "Error: ". $sql ." ". $conn->error; } $conn->close(); } } else{ echo "REASON should not be empty"; die(); } } else{ echo "USERID should not be empty"; die(); } } } ?> 上定义一个static方法,然后在A中使用它(而不实例化B)。

A

相关问题