其擴充方法的觀念和用途就不再說明了,我們直接看程式碼範例:
//String擴充方法 - Contains
String.prototype.Contains = function(str){
    return (this.indexOf(str) != -1);
}
//String擴充方法 - IsFilled
String.prototype.IsFilled = function () {
    if (this && this.length > 0) {
        return true;
    }
    return false;
}
//String擴充方法 - IsEmpty
String.prototype.IsEmpty = function () {
    return !this.IsFilled();
}
//function擴充方法 - getData
sample.prototype.getData = function() { 
 return this.i; 
}
使用擴充方法
//String使用擴充方法
var name="This is JS Test";
alert("foobar".Contains("foo")); //alerts true
alert(name.IsFilled()); //alerts true
alert(name.IsEmpty()); //alerts false
//Function使用擴充方法
function sample(i) { 
    this.i = i;     
}
var s = new sample(42);
alert(s.getData()); //alerts 42
附上個人常用的擴充方法,可以直接參考使用,有錯誤再請指教^^
參考來源:StackOverflow、ExtensionMethod.NET
 
沒有留言:
張貼留言