此处对比ES6类来说明ES5的原型
ES6类
// class Box{
// static b=2;属于类
// a=1;属于实例
// constructor(_a){
// this.a=_a;
// }
// play(){属于实例
// //动态方法 实例方法
// }
// static run(){属于类
// }
// }
ES5:
任何函数都有一个prototype属性,给构造函数设置prototype属性,就是给该类设置属性
function Box(_a) {相当于ES6中的类Box
this.a = _a;
// 构造函数中不能返回对象,不要使用return
// return {a:1,b:2};
}
Box.b = 2;
Box.run = function () { }
Box.prototype.a=1;
Box.prototype.play=function(){}
这种写法会将实例化出的对象的构造函数给覆盖掉,解决:可以重写构造函数
Box.prototype = {
a: 1,
play: function () {
// this-->实例化的对象
}
}
覆盖构造函数之前:
覆盖构造函数之后:
解决之后:
//这种写法不会覆盖掉类的构造函数
function Ball(){
}
Object.assign(Ball.prototype,{
a:1,
b:function(){
}
})
var b=new Ball();
b.a=100;
console.log(b);
console.log(b.constructor===Box);
console.log(b.__proto__===Box.prototype);
//类的原型就是该实例化对象的原型链
//在类的原型上设置方法,所有通过该类实例化的对象都具备这个方法
//原型链仅针对对象来说,针对对象来观察该类的原型方法和原型属性
//给类的原型添加forEach方法
// Array.prototype.forEach1=function(fn){
// for(var i=0;i<this.length;i++){
// fn(this[i],i,this);
// }
// }
// var arr=[1,2,3,4];
// arr.forEach1(function(item,index,arr){
// console.log(item,index,arr);
// })
//给Object添加forEach方法:
// Object.defineProperty(Object.prototype,"forEach",{
// value:function(fn){
// for(var prop in this){
// fn(this[prop],prop,this);
// }
// }
// })
// var divs=document.querySelectorAll("div");
// divs.forEach(function(item,index,obj){
// console.log(item,index,obj)
// })
//给HTMLElement的原型添加styles
Object.defineProperties(HTMLElement.prototype, {
_styles: {
value: null,
writable: true
},
styles: {
set: function (value) {
this._styles = value;
for (var prop in value) {
this.style[prop] = value[prop];
}
},
get: function () {
return this._styles;
}
}
})
var div = document.querySelector("div");
console.log(div);
div.styles = {
width: "50px",
height: "50px",
backgroundColor: "green"
}