如何克服"可能无效使用此"?

时间:2016-11-15 08:49:08

标签: javascript

在调用from app import app from flask import Blueprint, request handlers = { 'inspection': None, 'data': None, 'repeat': None } handler_page = Blueprint(START_URL, __name__) # Ideally register this blueprint where you registered your app app.register_blueprint(handler_page) @handler_page.route('/<string:handler_type>', methods=['GET']) def handler_view(handler_type): try: curr_handler = handlers[handler_type] except KeyError: return "Not found.", 404 return curr_handler.update(request) 如何克服以及如何正确调用this时,我可能无效使用isDataMatchingnamespace

isDataMatchingnamespace

4 个答案:

答案 0 :(得分:5)

这是this的无效用法,因为this在该函数中是undefined

underscore.js允许您将可选的附加参数传递给forEach,以指定函数内应该this。如果您希望它与函数外部的this相同,则将this作为第三个参数传递给_.forEach

    _.forEach(datas, function(data) {
        if (this.isdataMatchingnamespace(data)) {
            result.push(data);
        }
    }, this); // Added ", this"

答案 1 :(得分:3)

还有其他方法可以将此值存储到变量中。

让我们说var _thisRef = this;var namespace = "default";下方定义,并在不更改代码的情况下使用_thisRef.isdataMatchingnamespace(data)

您的更新代码如下:

function Client() {

var namespace = "default";
var _thisRef = this;

this.addnamespaceTodata = function(data) {
    data.namespace = namespace;
    return data;
};

this.isdataMatchingnamespace = function(data) {
    return data.namespace === namespace;
};

this.filterdatasBynamespace = function(datas) {
    var result = [];
    _.forEach(datas, function(data) {
        if (_thisRef.isdataMatchingnamespace(data)) { // I get potentially invalid usage of this so how to overcome and how to call isDataMatchingnamespace in a proper way?
            result.push(data);
        }
    });
}
}

module.exports = Client;

答案 2 :(得分:0)

另一种更好的方法是在类级别声明变量,例如:

export class SomeComponent {someVarible = []; }

someFunction() { const tempVar = []; _.forEach(datas, function(data) { 
                  tempVar.push(data) // now use this variable to pass or
                  assign the data 
               }, this); 
                       this.someVarible = tempVar;
                          // OR
                       otherFunction(tempVar); // where you can use your varuiable
 }

答案 3 :(得分:-1)

es6箭头功能会自动为您完成!

只需将语法更改为箭头函数语法

数据=> { 你的功能在这里 }