一.首先给出一道经典的原型题目:
var F = function(){}; Object.prototype.a = function(){}; Function.prototype.b = function(){}; var f = new F();
f能否调用a方法与b方法。
通过原型链:1.f----->F.prototype-------->Object.prototype------------>null。2.F--------->Function.prototype------------>Object.prototype------------->null
可知f只能调用a方法,而F可以调用a,b方法。
typeof undefined;//undefined
typeof Null;//undefined
typeof Boolean;//function
typeof Number;//function
typeof String;//function
typeof Object;//function
typeof Function;//function
typeof function(){};//function
从上述可得Number等--------->Function.prototype--------->Object.prototype---------->null;
得到题目中的F的原型也为Function.prototype
而f的原型为F.prorotype与F的原型无关。
例子:
Function.prototype.method = function(name, func) { if(!this.prototype[name]) { this.prototype[name] = func; } } var a = [1, 2, 3, 4, 5]; Array.method("reduce", function(f, value) { for(var i = 0; i < this.length; i++) { value = f(this[i], value); } return value; })//方式一 Array.reduce = function(f, value) { for(var i = 0; i < this.length; i++) { value = f(this[i], value); } return value; }//方式二 a.reduce = function(f, value) { for(var i = 0; i < this.length; i++) { value = f(this[i], value); } return value; }//方式三 var add = function(a, b) { return a + b; } var sum = a.reduce(add, 0); console.log(sum);//15
二.对象中存在一个指向相关原型的链接,__proto__属性。