1. 程式人生 > >給對象和函數添加method方法

給對象和函數添加method方法

fin 屬性 我們 truct struct per 內容 不能 是個

蝴蝶書中有一個method方法,用來給函數定義方法。看了之後,想著能不能給對象也定義方法呢?、

下面的代碼可以實現給函數定義方法:

 //Function method
Function.prototype.method = function (name,func) {
    this.prototype[name] = func;
    return this;
}

在實現給對象定義方法的過程中,我遇到了一些問題,對象是沒有prototype的。

經過思考,用下面的方法實現了給對象定義方法的功能,但是比較繁瑣:

//Object method
Object.prototype.method = function
(name,func) { Object.prototype[name] = func; //不能用this,因為a沒有prototype屬性 return this; } //該方法的缺點是,一旦給某對象定義了方法,所有對象都將擁有該方法。

關於prototype和__proto__的思考:

var Person = function(arg1,arg2,...){};
var p = new  Person();

等價於:

1 var p={};  //也就是說,初始化一個對象p。
2 p.__proto__=Person.prototype;
3 Person.call(p,arg1,arg2,...);  //
也就是說構造p,也可以稱之為初始化p(沒有這一步,p是空的)。

其中:
p.__proto__ == Person.prototype;
Person.prototype:
Object {constructor: function}
函數Person的prototype是Person的一個屬性,該屬性是個對象,這個對象是p的原型。。

另外,由於 Person.call(p,arg1,arg2,...)構造p

使得p.construtor === Person();

我們生成一個Object和一個Function的來探尋這些內容的關系:
var a = new Object();
var b = new Function();

a.__proto__ == Object.prototype;
b.__proto__ == Function.prototype;


低層次,以下3個指向同一內容。
function () { [native code] }
1、 Function.prototype
2、 Object.__proto__
3、 Function.__proto__

高層次,以下4個指向同一內容。
Object {__defineGetter__: function, __defineSetter__: function, hasOwnProperty: function, __lookupGetter__: function, __lookupSetter__: function…}
1、 Object.prototype
2、 Function.prototype.__proto__
3、 Object.__proto__.__proto__
4、 Function.__proto__.__proto__
所以只有Function method,不定義Object method我們也照樣會看到Object.method;
但是對於

var a = new Object();

Object並不是a的原型,所以a也不存在method方法。a的原型在高層次。
此時,我們為Object.prototype定義method方法,這是a的上級原型鏈,a就有了method方法.

註意:
既然Object method層次更高,就算沒有Function method也無所謂。但是這可能涉及安全性問題。
如果既有Function method又有Object method
我們給Function添加method方法時,會調用Function method(從低向高查找method)
我們給Object添加method方法時,會調用Object method

給對象和函數添加method方法