简体   繁体   English

在 class model.js 中调用 function

[英]calling a function inside class model.js

I have 2 functions inside model.js, findUser(id) and findById(userId).我在 model.js 中有 2 个函数,findUser(id) 和 findById(userId)。 they are both inside class.它们都在 class 内。 Inside findById(userId), I want to call findUser(id).在 findById(userId) 中,我想调用 findUser(id)。 how can I do that?我怎样才能做到这一点?

findUser(id) {
                let foundUsers = users.filter(function(user) {
                    if(user.id === id) {
                        return true;
                    }
                    return false;
                });
    
                if(foundUsers.length > 0) {
                    return foundUsers[0];
                } else {
                    return null;
                }
            }
    
    
    
         findById(userId) {
            // Find user by Id
            // Returns user, or null if not present
    }

Usually it's not a good practice to call a method inside a model class.通常在 model class 中调用方法不是一个好习惯。 So better create a model object out side and call each functions accordingly.所以最好在外面创建一个 model object 并相应地调用每个函数。

Create a new object of that class创建该 class 的新 object

let model1 = new Model();

Call that function using dot operator.使用点运算符调用 function。

model1.findUser(id);
model1.findById(userId);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM