js面向對象編程: js類定義函數時prototype和this差別?
阿新 • • 發佈:2017-06-23
this script 私有字段 new art func 內部 name prot
this.do1=function ()和ListCommon2.prototype.do2=function()有什麽差別呢?
經過測試發現:this.do1能夠訪問構造函數內部的變量first。而ListCommon2.prototype.do2不能訪問,但能訪問函數this.do1。
在面向對象編寫js腳本時,定義實例方法主要有兩種
例如以下:
function ListCommon2(afirst) { var first=afirst; this.do1=function () { alert("first do"+first); } } ListCommon2.prototype.do2=function() { // alert("first do"+first);//會出錯。不能訪問first this.do1(); }
this.do1=function ()和ListCommon2.prototype.do2=function()有什麽差別呢?
都相當於類的實例方法,僅僅有new後才幹使用。那有什麽差別呢?
測試代碼:
var t2=new ListCommon2("燒水2"); t2.do1();// t2.do2();//
經過測試發現:this.do1能夠訪問構造函數內部的變量first。而ListCommon2.prototype.do2不能訪問,但能訪問函數this.do1。
假設把ListCommon2.prototype.do2定義在構造函數內部,也就可訪問了。但作為實例函數。假設定義在構造函數內部,每次實例化都要運行。顯然在浪費內存,也不合理。
有些資料上把this.do1這類方法叫做特權方法。主要是為了訪問內部的私有字段,這樣就能夠控制對某些字段的訪問。比如如上,就定義了一個私有字段first,僅僅能通過構造函數傳遞,然後就不能改動了。
ListCommon2.prototype.do2這類方法相當於類的實例方法。但能訪問這些特權方法,間接訪問私有字段。
結論:
假設要直接訪問私有字段,應該使用特權方法,也就是this定義的方法。應該定義在構造函數內部。相反,假設不須要直接訪問私有字段,應該使用prototype定義的方法。並且應該定義在構造函數外部。
js面向對象編程: js類定義函數時prototype和this差別?