我如何添加自定义属性到javascript字符串对象

how can i add custom properties to javascript string object

本文关键字:自定义属性 javascript 字符串 对象 添加 何添加      更新时间:2023-09-26

我想为字符串对象定义我自己的自定义属性,所以我可以直接在字符串对象上使用这个属性。STR是我的字符串对象。那么我应该能够使用.IsNull属性,如下所示。

var str = “string”;
str.IsNull; //returns true if null
str.IsEmpty; returns true if empty

您可以探索prototype property

例如

String.prototype.yourMethod = function(){
 // Your code here
}

感谢大家的帮助。但我得到了方法

Object.defineProperty( String.prototype, 'IsNullOrEmpty', {
    get: function () {
        return ((0 === this.length) || (!this) || (this === '') || (this === null));
    }
});
var str = "";
str.IsNullOrEmpty;//returns true

您必须为String包装器对象的原型添加一个新方法。最佳实践是在声明该方法之前检查该方法是否已经存在。例如:

String.prototype.yourMethod = String.prototype.yourMethod || function() {
    // The body of the method goes here.
}

我个人会为此编写函数,而不是扩展原型。

如果你扩展原型,你必须确保你将它们添加到你想要检查的所有类型中,它超出了String对象。

function isNull(str) {
  console.log( str === null );
}
function isEmpty(str) {
  console.log( typeof str == 'string' && str === '' );
}
isNull(null);
isNull('');
isNull('test');
isEmpty(null);
isEmpty('');
isEmpty('test');