[英]how can i add custom properties to javascript string object
我想為字符串對象定義自己的自定義屬性,以便可以直接在字符串對象上使用此屬性。 例如:-str是我的字符串對象。那么我應該能夠使用.IsNull
屬性,如下所示。
var str = “string”;
str.IsNull; //returns true if null
str.IsEmpty; returns true if empty
您必須向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');
感謝你們所有人的幫助。
Object.defineProperty( String.prototype, 'IsNullOrEmpty', {
get: function () {
return ((0 === this.length) || (!this) || (this === '') || (this === null));
}
});
var str = "";
str.IsNullOrEmpty;//returns true
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.