我想为字符串对象定义我自己的自定义属性。所以我可以直接在字符串对象上使用这个属性。例如: - str是我的字符串对象。然后我应该可以使用.IsNull
属性,如下所示。
var str = “string”;
str.IsNull; //returns true if null
str.IsEmpty; returns true if empty
答案 0 :(得分:3)
答案 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