文章目录
原型的深入理解
- 每个函数都有是函数数据类型的实例,实例就会有
__proto__
属性,指向所属类的原型 Object基类
也是一个函数,所以Object.__proto__
也指向Function.prototype
- 函数的实例有
__proto__
和prototype
两个属性 Function基类自身
也是个函数,所以他自身也有一个__proto__
,指向所属类的原型,Function.prototype
原型拓展
一个方法重复使用时,可以直接将其定义为原型上的公有属性,例如
function Fn(name,age){
this.name=name;
this.age=age;
}
Fn.prototype.say=function(){
alert('我的名字是:'+this.name+'----我的年龄是:'+this.age);
}
var f1=new Fn("阿杰",18);
f1.say();
封装一个push
Array.prototype.myPush=function(){
for(var i=0;i<arguments.length;i++){
// this[this.length]=arguments[i];
// this.splice(this.length,0,arguments[i]);
this.splice(this.length,1,arguments[i]);
}
return this.length;
}
var ary=[1,2,3];
console.log(ary.myPush(4,5,6,7));//返回数组长度7
console.log(ary);//新数组[1,2,3,4,5,6,7]
链式调用
实现链式写法:保证每次函数执行完毕之后的返回结果是当前类的实例
//想要实现一个需求:
//var ary=[5,8,2,1,10] ;想要让这个数组先排序,然后再倒序,然后再往里面添加一个10,然后再删除第一项;
var ary=[5,8,2,1,10];
ary.sort(function(a,b){
return a-b}).reverse().push(10);//因为push返回值是10所以不能继续
ary.shift();
console.log(ary);//[8,5,2,1,10]
原型重定向
手动更改原型的指向
,没有constructor,所以会沿着原型链查找,找到Object.prototype的constructor===>Object</