为什么在函数中使用`this`会给我一个“可能的严格违规”。在jshint? [英] Why does using `this` within function give me a "Possible strict violation" in jshint?

查看:108
本文介绍了为什么在函数中使用`this`会给我一个“可能的严格违规”。在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
};

我的目标是能够调用 myObjOne.add(myData) 其中 myData 是我想要添加到 myObjOne 的对象,并且能够在 myObjTwo 上复制此功能。

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.

我的问题是使用这个 addToObject 给我:

My issue is that using this within addToObject gives me:

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

为什么会这样?

推荐答案

文档说警告发生了when:

The docs say the warning happens when:


你在非构造函数中使用 this 。如果在调用构造函数时忘记使用 new 关键字,将意外绑定到全局对象中非严格模式,但在严格模式下将是未定义的。

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.

使用 validethis:true in pragma comment:

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];
        }
    }
}

参考文献

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

这篇关于为什么在函数中使用`this`会给我一个“可能的严格违规”。在jshint?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆