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

时间:2016-09-12 07:04:52

标签: javascript string

我想为字符串对象定义我自己的自定义属性。所以我可以直接在字符串对象上使用这个属性。例如: - str是我的字符串对象。然后我应该可以使用.IsNull属性,如下所示。

var str = “string”;

str.IsNull; //returns true if null

str.IsEmpty; returns true if empty

4 个答案:

答案 0 :(得分:3)

您可以浏览prototype属性

例如

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

答案 1 :(得分:1)

您必须向String包装器对象的原型添加新方法。最佳做法是在声明方法之前检查方法是否已存在。例如:

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

答案 2 :(得分:1)

我个人会为此而不是扩展原型。

如果扩展原型,则必须确保将它们添加到要检查的所有类型,它超出了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');

答案 3 :(得分:1)

谢谢你们所有人的帮助。但我得到了方法

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

var str = "";
str.IsNullOrEmpty;//returns true