ja的prototype




(1)
網上對於prototype的文章很多,一直沒明白核心的思想。
最後寫了很多例子代碼後才明白:prototype只能用在類型上。






(2)
每一個構造函數都有一個屬性叫做原型(prototype,下面都不再翻譯,使用其原文)。
這個屬性非常有用:爲一個特定類聲明通用的變量或者函數。






(3)
prototype我自己感覺就像一個var prototype = new Object();
prototype.airuikun = "ahaha";
prototype.method = function(){}


但是它只能是一個類的一個屬性  而不能是一個對象的屬性




用法有點像html5的localStorage,不能直接使用 例如alert(localStorage)
而是給它附上屬性跟方法才能使用








(4)注意事項:::!!!!
只能通過類來調用這個屬性
絕對不能用對象和實例來調用這個屬性


正確
Class.prototype.a = 1;   
alert(Class.prototype.a);//ok


錯誤
Class.prototype.a = 1; 
var color = new Class();
alert(color.prototype.a); //error












(5)例子




(1)可以在類型上使用proptotype來爲類型添加行爲。這些行爲只能在類型的實例上體現。
Object.prototype.Property = 1;
Object.prototype.Method = function ()
{
   alert(1);
}
 
var obj = new Object();
alert(obj.Property);
obj.Method();



JS中允許的類型有Array, Boolean, Date, Enumerator, Error, Function, Number, Object, RegExp, String








(2)在實例上不能使用prototype,否則發生編譯錯誤
var obj = new Object();
obj.prototype.Property = 1; //Error
//Error
obj.prototype.Method = function()
{
   alert(1);
}























(6)跟extend()可以做一個比較




jquery的extend和fn.extend
jQuery爲開發插件提拱了兩個方法,分別是:
 
jQuery.fn.extend(object);
jQuery.extend(object);
 
jQuery.extend(object); 爲擴展jQuery類本身.爲類添加新的方法。
jQuery.fn.extend(object);給jQuery對象添加方法。




jQuery是類
$()是jquery對象




增加兩個插件方法。


jQuery 代碼:
jQuery.fn.extend({
  check: function() {
    return this.each(function() { this.checked = true; });
  },
  uncheck: function() {
    return this.each(function() { this.checked = false; });
  }
});結果:
$("input[type=checkbox]").check();
$("input[type=radio]").uncheck();






也可以
在jQuery類上增加兩個函數。


jQuery 代碼:
jQuery.extend({
  min: function(a, b) { return a < b ? a : b; },
  max: function(a, b) { return a > b ? a : b; }
});結果:
jQuery.min(2,3); // => 2
jQuery.max(4,5); // => 5























發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章