es6中有类
es5中有构造方法
prototype
的属性,叫做原型属性对象中有一个__proto__
当这个函数仅仅是作为函数执行,那么这个prototype
是没有作用的但是当这个函数作为构造函数使用时,prototype
就是这个构造函数的原型属性构造函数 通常不是正常的执行函数方式,而是需要通过new 构造函数() 执行普通函数执行只是执行函数中的语句,并且可能返回一个值构造函数执行通过new 构造函数,这时候,我们把构造函数作为一个类的类名,并且根据这个类名实例化一个对象,这个实例化的对象中包含的原型链属性中就具备了构造函数中Prototype对象的所有属性方法,同时构造函数不能返回任何值,否则替代实例化对象在实例化对象中__proto__实际上就是构造函数prototype类的
prototype
就是实例化对象的__proto__
es5 构造函数创造实例化对象
function Box(){
console.log("aa");
// 同时构造函数中不能使用return
}
Box.prototype.a=1;
Box.prototype.play=function(){
console.log("play")
}
var b=new Box();//这种方式叫做通过构造函数创造实例化对象
console.log(b)
console.log(b.__proto__===Box.prototype);//true
案例一
class Box{
a=1;
static b=2;
_step=1;
constructor(_a){
this.a=_a;
}
play(){
console.log("a")
}
static setCSS(){
console.log("css");
}
set step(value){
this._step=value;
}
get step(){
return this._step;
}
}
/* 构造函数constructor */
function Box(_a){
this.a = _a;
}
/* 实例化属性和方法 */
Box.prototype.a =1;
Box.prototype.play = function(){
console.log("play");
}
/* 静态属性和方法 */
Box.b=2;
Box.setCSS= function(){
console.log("css");
}
/* get,set */
Object.defineProperties(Box.prototype,{
_step:{
value:1,
},
step:{
set(value){
this._step = value
},
get(){
return this._step;
}
}
})
案例二
class Box{
a=1;
_values=1;
static list=[]
constructor(){
this.play();
}
play(){
document.addEventListener("click",e=>this.clickHandler(e))
}
clickHandler(e){
this.a++;
}
static run(){
Box.list.push(this);
}
set values(v){
this.a=v;
this._values=v;
}
get values(){
return this._values
}
}
/* 构造函数constructor */重构chunk
function Box(){
this.play();
}
/* 实例化属性和方法 */
Box.prototype.a = 1;
Box.prototype.play = function(){
document.addEventListener("click",this.clickHandler.bind(this));
}
Box.prototype.clickHandler = function(e){
this.a++;
}
/* 静态属性和方法 */
Box.list = [];
Box.run = function(){
Box.list.push(this);
}
/* get,set */
Object.defineProperties(Box.prototype,{
_values:{
value:1
},
values:{
set(v){
this.a=v;
this._values=v;
},
get(){
return this._values
}
}
})
Array.prototype.chunk=function(num){新写css方法
var arr=[[]];
for(var i=0;i<this.length;i++){
if(arr[arr.length-1].length===num) arr.push([]);
arr[arr.length-1].push(this[i]);
}
return arr;
}
var arr=[1,2,3,4,5,6,7,8];
var arr1=arr.chunk(3);
console.log(arr1)
var div = document.createElement("div");函数柯里化方法
document.body.appendChild(div);
HTMLElement.prototype.css = function(style){
for(var key in style){
if(/width|height|top|right|left/.test(key)){
this.style[key] = isNaN(style[key])?style[key]:Number(style[key])+"px"
}else{
this.style[key] = style[key]
}
}
}
div.css({
width:200,
height:400,
backgroundColor:"green"
})
Function.prototype.currying = function(){全网最优原型继承,肝
var arr =[];
var fn = this;
return function(){
if(arguments.length>0){
arr = [...arr,...arguments];
return arguments.callee;
}else{
return fn(...arr);
}
}
}
function getSum(){
return Array.from(arguments).reduce((v,t)=>v+t);
}
var f1 = getSum.currying();
f1(1,2,3)
console.log(f1());