简体   繁体   English

如何在不获取JSHint问题的情况下扩展javascript字符串?

[英]How can I extend javascript String without getting a JSHint Issue?

Hi I am extending String using prototype but JSHint throws a warning: 嗨我正在使用原型扩展String但JSHint会发出警告:

Extending prototype of native object: 'String'. 扩展原生对象的原型:'String'。

How should I be tackling this? 我应该怎么解决这个问题? I assume the warning is down to this method being considered bad practice. 我认为警告是由于这种方法被认为是不好的做法。

String.prototype.decodeHTML = function() {

    return $('<div>', {html: '' + this}).html();

};

Any help would be greatly appreciated, thanks. 非常感谢任何帮助,谢谢。

UPDATE This does actually work: 更新这确实有效:

Here's the solution for those that want it. 这是那些想要它的人的解决方案。

Object.defineProperty(String.prototype, "decodeHTML", {
    value: function () {
         return $('<div>', {html: '' + this}).html();
    }
});

See JSLint Docs: https://jslinterrors.com/extending-prototype-of-native-object . 请参阅JSLint文档: https ://jslinterrors.com/extending-prototype-of-native-object。 You should use 你应该用

Object.defineProperty(String.prototype, "decodeHTML", ...)

instead. 代替。

The warning in question should only be issued when the freeze option is enabled. 只有在启用freeze选项时才会发出有问题的警告。 You can disable that option for the relevant block (or file) by using a directive comment: 您可以使用指令注释为相关块(或文件)禁用该选项:

/*jshint freeze: false */
String.prototype.decodeHTML = function() {

    return $('<div>', {html: '' + this}).html();

};

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

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