简体   繁体   English

可能严格违反-对JavaScript函数使用原型方法

[英]Possible strict violation - using prototype method for JavaScript function

I am getting the following issue with my code. 我的代码出现以下问题。 I have a function that will take product data and then return it. 我有一个将获取产品数据然后返回的函数。 We have many options on what we can sort the data on (for example price, name, data, stock levels, etc). 关于数据的排序方式,我们有很多选择(例如价格,名称,数据,库存水平等)。 Now I pass my data (which is in a JSON format) and depending on the option that is set as an argument I perform the data transform, however I get the following error when I run my code: Possible strict violation. 现在,我传递数据(采用JSON格式),并根据设置为参数的选项进行数据转换,但是在运行代码时出现以下错误: Possible strict violation.

This is my function to sort the data: 这是我对数据进行排序的功能:

// this is how i call the function, the data argument is the JSON data and formatting options are set in an object literal - this determines the data by name

dataSort(data, {'name':'product name'});

function dataSort(d, obj) {
// we do lots of stuff then later in the function   
for (var key in obj) {
        if(obj.hasOwnProperty(key)){
            if(key === 'name'){
                d = this.getProductByName(d, obj[key]); // This line produces the error
            }
        }
    }
    return d;
}

dataSort.prototype.getProductByName = function(data, val){
    // do stuff the return data
    return data;
};

Now I was alway taught to use the prototype when creating internal methods on functions, why am I getting my error? 现在总是被教导要在函数上创建内部方法时使用原型,为什么会出现错误? What am I doing wrong? 我究竟做错了什么? Should I use a private method or an internal method using this.getProductByName = function(){} Any help will be appreciated. 我应该使用私有方法还是使用内部方法(使用this.getProductByName = function(){}将不胜感激。

The correct way to define private helper functions is to use a closure. 定义私有助手功能的正确方法是使用闭包。

var datasort = (function () {
    var getProductByName = function (data, val){
        // do stuff
        return data;
    };

    return function datasort(d, obj) {
        var key;

        // do lots of stuff ...
        return getProductByName(d, obj.name);
    };
}());

getProductByName is now only visible to the inner datasort function (which gets assigned to a variable of the same name). getProductByName现在仅对内部数据datasort功能可见(该功能已分配给同名变量)。

The effect of the closure is that getProductByName is created only once, instead of with every call of datasort (that would be the case if you moved var getProductByName ... into function datasort ). 闭包的作用是,只创建一次getProductByName ,而不是每次调用datasort都会创建一次(如果将var getProductByName ...移到function datasort )。

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

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