Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/400.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在javascript的另一个类中使用函数_Javascript_Html_Function_Class - Fatal编程技术网

在javascript的另一个类中使用函数

在javascript的另一个类中使用函数,javascript,html,function,class,Javascript,Html,Function,Class,我这里有这段代码,我想在另一个类中使用validate result(false),我该怎么做?我找不到它 class Login extends Base { constructor(propertyValues) { super(propertyValues); } validate { var usernamed = document.getElementById("username").value; var pa

我这里有这段代码,我想在另一个类中使用validate result(false),我该怎么做?我找不到它

class Login extends Base {

    constructor(propertyValues) {
        super(propertyValues);
    }

    validate {
        var usernamed = document.getElementById("username").value;
        var passworded = document.getElementById("password").value;
        if (usernamed == "abc" && passworded == "123") {
            alert("Login successfully");
            window.location = "http://localhost:3000/tasksMenu"; // Redirecting to other page.
            return false;
        }
    }
}

首先,类中存在语法错误。应将验证函数定义为:

validate() {
//...
}
您可以在另一个类中访问此函数,前提是该函数在此类之后加载。例如,您可以按如下方式访问它:

class other {
    access() {
        var login = new Login("pass your property values");
        console.log(login.validate());
    }
}
new other().access();

您可以将validate设置为static,因为它对类“
this
没有任何作用,而且看起来非常静态。其次,我不会将重定向逻辑放在验证函数中,而是在稍后调用验证的函数中处理重定向。因此,只需使
validate()
返回true或false,然后从调用它的位置处理其余部分:

class Login extends Base {

    constructor(propertyValues) {
        super(propertyValues);
    }

    static validate() {
        let usernamed = document.getElementById("username").value;
        let passworded = document.getElementById("password").value;
        return usernamed == "abc" && passworded == "123";
    }
}

class Foo {
    bar() {
        if (Login.validate()) {
            alert("success");
            // redirect to your success page
        } else {
            alert("wrong credentials");
            // redirect to your error page
        }
    }
}

new Foo().bar();

旁注:


既然您已经用html和javascript标记了它,我假设您正在编写一个前端登录系统?如果是这样,不要这样做!前端的所有内容都可以被使用你网站的每个人阅读;这包括您检查的密码和用户名在后端登录

在使用“验证结果”的方法中,验证应采用以下格式
validate(){}