给对象和函数添加method方法

蝴蝶书中有一个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

最后一个例子:

var arr = new Array();
arr.__proto__ === Array.prototype;
//true
arr.constructor === Array;
//true
arr.__proto__ === arr.constructor.prototype;
//true
原文地址:https://www.cnblogs.com/miaodi/p/6858879.html