闭包和继承

闭包:由于作用域嵌套,形成了一种特殊现象,局部的局部,每次执行完以后,会改变局部变量,每次调用局部的局部,局部变量没有重新开始,会从上一次调用的结果开始

function fn(){
    var a = 2;
    return function(){
        a++;
        console.log(a);
    }
}

var fun = fn()
fun()
fun()

闭包应用场景:循环中绑定事件、循环中执行异步操作都可以使用闭包来解决

闭包特点:

1.延长的变量的声明周期
2.保护了私有的变量
3.函数的作用域一直没有被销毁
 
缺点:容易造成内存的溢出
 

继承:儿子拥有父亲的财产

有关于对象的继承 - 原型继承

function Father(){
    this.height = '很高';
}

function Son(){

}
var f = new Father;
Son.prototype = f
var s = new Son()

console.log(f,s);

原型继承的弊端

function Father(name,age){
    this.name = name
    this.age = age;
    this.height = '很高';
}

function Son(){

}
// 在继承的时候,不知道传什么参数比较好
Son.prototype = new Father('张三',20)
// 没办法给父对象传参
var s = new Son('lisi',21)
console.log(s);

借用函数继承

function Father(name,age){
    this.name = name
    this.age = age;
    this.height = '很高';
}

Father.prototype.eat = function(){
    console.log("很能吃");
}

// 借用函数继承/上下文调用模式继承
function Son(name,age){
    Father.call(this,name,age)
    // 执行Father中的代码,并且将Father中的this变成当前的this
    // this.name = name
    // this.age = age;
    // this.height = '很高';
}

var s = new Son('李四',21)
console.log(s);
s.eat()
// 借用函数继承的弊端 - 没办法继承父亲原型上的方法

混合继承

// 两种继承方式都用一遍 - 混合继承
function Father(name,age){
    this.name = name
    this.age = age;
    this.height = '很高';
}

Father.prototype.eat = function(){
    console.log("很能吃");
}

function Son(name,age){
    Father.call(this,name,age)
}

Son.prototype = new Father()

var s = new Son('李四',21)
console.log(s);
s.eat()

es6 - class类

类:抽象的对象 - 构造函数==类
对象:实例化的类
语法:
class 类名{

}

eg:

class Person{
    // 如果需要给对象添加属性,就需要在类中定义方法 - constructor
    constructor(name,age){ // new的时候,其实就是在调用constructor这个方法
        this.name = name
        this.age = age
    }
    // 如果要给对象添加方法 - 在类中继续定义方法
    eat(){
        console.log("能吃");
    }
}

var p = new Person('张三',12)
console.log(p);

 

posted @ 2021-02-01 11:35  技术活当赏  阅读(58)  评论(0)    收藏  举报