Why does using `this` within function give me a “Possible strict violation” in jshint?

邮差的信 提交于 2020-01-03 06:01:07

问题


Say I have a function that I would like reuse as a method on a couple objects in order to add data to those objects.

function addToObject(data) {
  for (var d in data) {
    if (data.hasOwnProperty(d)) {
      this[d] = data[d];
    }
  }
}

myObjOne = {
  add: addToObject
};

myObjTwo = {
  add: addToObject
};

My goal here was to be able to call myObjOne.add(myData) where myData is an object that I would like to add to myObjOne and be able to replicate this functionality on myObjTwo.

My issue is that using this within addToObject gives me:

this[d] = data[d];
^ Possible strict violation.

in jshint.

Why is this?


回答1:


The docs say the warning happens when:

you use this in a non-constructor function. If you forget to use the new keyword when calling a constructor function, this will be bound unexpectedly to the global object in non-strict mode, but will be undefined in strict mode.

Use validethis:true in a pragma comment:

function addToObject(data) {
    'use strict';
    var d;
    for (d in data) {
        if (data.hasOwnProperty(d)) {
            /* jshint: validthis:true */
            this[d] = data[d];
        }
    }
}

References

  • JsHint Options: validthis
  • The Strict Mode Restriction and Exceptions


来源:https://stackoverflow.com/questions/23146955/why-does-using-this-within-function-give-me-a-possible-strict-violation-in-j

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!