简体   繁体   English

为什么在函数jshint中使用`this`会给我一个“可能的严格违反”?

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

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 . 我的目标是能够调用myObjOne.add(myData) ,其中myData是要添加到myObjOne的对象,并能够在myObjTwo上复制此功能。

My issue is that using this within addToObject gives me: 我的问题是在addToObject中使用this可以给我:

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

in jshint. 在jshint中。

Why is this? 为什么是这样?

The docs say the warning happens when: 文档说警告发生在以下情况:

you use this in a non-constructor function. 您可以在非构造函数中使用this 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. 如果您在调用构造函数时忘记使用new关键字, this它将在非严格模式下意外绑定到全局对象,但在严格模式下将未定义。

Use validethis:true in a pragma comment: validethis:true注释中使用validethis:true

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

References 参考

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

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