原型語法數組
function Student(name,id){ this.name = name; this.id = id; } //獲取對象的prototype Student.prototype.type = "student"; Student.prototype.message = function(){ console.log(this.name + "," + this.id); }; //生成實例對象 var student1 = new Student("li",111);
直接使用一個對象字面量對原型對象進行賦值函數
Student.prototype = { type : "student", message : function(){ console.log(this.name + "," + this.id); } }; //能夠正常調用 student1.message();
可是,須要注意有一點,student1.constructor
的指向已經發生了改變,由於Student的prototype已經被重置了,constructor的指向找不到,student1.constructor
的值就變成了Object了。this
解決這一問題,很簡單,就是在給Student.prototrpe
的字面量對象賦值時,須要手動的將constructor屬性指向正確的構造函數。prototype
constructor : Student //該構造函數是Student
在定義構造函數時,使用原型對象時建議根據成員的功能不一樣,能夠分爲如下兩種進行設置:code
①私有成員,通常就是非函數成員,放到構造函數中;對象
②共享成員,通常就是函數,放到原型對象種;ip
當重置了prototype時,記得修正constructor的指向開發
JS 原生構造函數的原型對象get
全部函數都有prototype屬性對象原型
JavaScript中的內置構造函數也有prototype原型對象屬性:
- Object.prototype
- Function.prototype
- Array.prototype
- String.pprototype
- Number.protoptype
......
擴展數組的原型方法
直接給原型對象添加一個對象字面量的值是不行的,內置構造函數有其保護機制(因此以下這種代碼不容許的)。
Array.prototype = { getSum = function(){ var sum = 0; for(var i = 0;i < this.length;i++){ sum += this[i]; } return sum; } }; console.dir(Array.prototype);
直接使用Array調用prototype給其添加新屬性
Array.prototype.getSum = function(){ var sum = 0; for(var i = 0;i < this.length;i++){ sum += this[i]; } return sum; }; console.dir(Array.prototype);
實際開發中是不容許更改JS原生內置對象。