ES5的类和原型
- 在es5中,如果函数作为构造函数使用,也就是要通过new实例化,就需要将函数的首字母大写
- 实例化的对象 --------> proto 原型链
- 类(构造函数)---------> prototype 原型
首先来看一下写在对象上的属性方法和写在原型上的属性方法有什么区别?
1、写在对象上的方法:b对象有play方法,c对象没有play方法,所以无法调用play方法
var b=new Box();
b.a=10;
b.play=function(){
console.log(this.a);
}
b.play();
var c=new Box();
c.play();//
2、写在原型上的方法:只要通过实例化new出来的对象,都可以调用该原型链上的方法
// 如果函数作为构造函数使用,也就是要通过new实例化
// 就需要将函数的首字母大写
function Box(){
}
Box.prototype.a=1;
Box.prototype.abc=function(){
console.log(this.a);
}
// 实例化 将函数作为构造函数,通过new的方法将函数作为类来实现一个实例
var b=new Box();
b.a=10;//当前b对象的对象属性上设置10,不能设置原型链上的属性
var c=new Box();
b.abc();//打印10 直接获取对象属性
c.abc();//1
//如果对象下有对象属性,直接调用对象属性,如果没有对象属性,就查找它的原型链中离他最近原型属性
案例:给数组的原型上添加一个substring的方法,截取a到b之前的值
Array.prototype.substring=function(start,end){
if(start<0) start=0;
if(end<0) end=0;
if(end<start) [end,start]=[start+1,end+1];//解构赋值 交换结果
var arr=[];
for(var i=start;i<end;i++){
arr.push(this[i]);//this是是arr,arr执行的substring
}
return arr;
}
var arr=[1,2,3,4,5];
var a=arr.substring(2,4); //打印3,4
var a=arr.substring(4,2);//打印4,5
console.log(a);
案例1:给html元素设置添加宽高背景的方法
所有的html元素都会继承HTMLElement上的方法,所以给HTMLElement设置原型方法,这样html元素就可以调用该方法
HTMLElement.prototype.width=function(value){
if(value.constructor===Number) value+="px";
this.style.width=value;//谁调用这个方法,this就是谁
return this;//如果需要连缀,则需要返回this
}
HTMLElement.prototype.height=function(value){
if(value.constructor===Number) value+="px";
this.style.height=value;
return this;
}
HTMLElement.prototype.bg=function(value){
this.style.backgroundColor=value;
return this;
}
var div=document.createElement("div");
div.width(100);
div.height(100);
div.bg("red");
div.width(100).height(100).bg("red");
document.body.appendChild(div);
案例1:给html元素设置添加宽高背景的属性
Object.defineProperties(HTMLElement.prototype,{
w:{
set:function(value){
if(value.constructor===Number) value+="px";
this._w=value;
this.style.width=value;
},
get:function(){
return parseFloat(this._w);
}
},
h:{
set:function(value){
if(value.constructor===Number) value+="px";
this._h=value;
this.style.height=value;
},
get:function(){
return parseFloat(this._h);
}
},
bg:{
set:function(value){
this._bg=value;
this.style.backgroundColor=value;
},
get:function(){
return this._bg;
}
}
})
var p=document.createElement("p");
p.w=50;
p.h=50;
p.bg="green";
document.body.appendChild(p);//创建一个宽50 高50 绿色的p元素
console.log(p.w);//打印50
案例3:实现柯里化
Function.prototype.currying=function(){
var self=this;
var list=[];
return function(){
if(arguments.length>0){
list=list.concat.apply(list,arguments);
return arguments.callee;
}
return self.apply(null,list);
}
}
var fns=getSum.currying();
fns(1,3,5);
fns(6,8,2);
var s=fns();
console.log(s);
案例4:实现bind
Function.prototype.bind1=function(obj){
var self=this;
return function(){
return self.apply(obj,Array.from(arguments));
}
}
var obj={
a:1,
b:function(){
document.addEventListener("click",this.c.bind1(this));
},
c:function(e){
console.log(this.a)
}
}
obj.b();