Javascript-senior_继承

56 阅读2分钟

继承

// 父级的对象
    var parent = {
        myName: 'parent',
        money: 10000000,
        house: ['商铺', "住宅"],
        tech: function() {
            console.log('卖房子')
        }
    }

    var son = {
        myName: 'son'
    }

    // for in循环会遍历对象中的每一个属性
    for (const pKey in parent) {
        console.log(pKey, '-----', parent[pKey])
        if (pKey === 'myName') {

        } else {
            // son[pKey] 也是能够给对象添加属性的
            son[pKey] = parent[pKey]
        }

        if (son[pKey]) {
            continue
        }
        // son[pKey] 也是能够给对象添加属性的
        son[pKey] = parent[pKey]
    }

    // console.log(son)

    // 封装为一个函数,来实现对象之间的继承
    function extend(parent, child) {
        for (const pKey in parent) {
            if (child[pKey]) {
                continue
            }
            // son[pKey] 也是能够给对象添加属性的
            child[pKey] = parent[pKey]
        }
    }

    extend(parent, son)
    console.log(son)
    

原型继承

       // 学生类、教师类
function Person(name, age, sex) {
    this.myName = name
    this.age = age
    this.sex = sex
}

function Student(score) {
    this.score = score
}

function Teacher(salary) {
    this.salary = salary
}

// 实现了继承的第一种方式:原型继承
Student.prototype = new Person("zs",20,"男")
Student.prototype.constructor = Student // 注意!!!!!

var s1 = new Student(89)
console.log(s1)

call方法

函数本身就是一个对象,函数可以有自己的属性和方法

call方法就是用来执行某个函数的

    function fn(a,b){
   console.log(this) // 谁调用this,this就是谁
   console.log(a + b)
   }
   // 默认是通过Window来调用fn,但是有时候希望通过自定义的对象来调用fn
var obj = {
   myName:'zs'
}

// 报错:Uncaught TypeError: obj.fn is not a function
// 两种可能:1、obj中不存在fn这样的方法  2、obj中有存在fn,但fn不是方法,可能只是普通的属性
// obj.fn(3,4)

// 通过call方法,让自定义的对象能够调用指定的方法(函数)
// call方法在调用函数的时候,有两个作用:
// 1、执行指定的函数  fn(3,4)
// 2、改变调用的函数内部的this的值
fn.call(obj,3,4)
    

构造函数的属性继承

function Person(name,age,sex){
    this.myName = name
    this.age = age
    this.sex = sex
}

function Student(name,age,sex,score){
    Person.call(this,name,age,sex)
    this.score = score
}

var s1 = new Student("zs",20,"女",90)

console.dir(s1)

image.png

构造函数的方法继承

<script>
function Person(name,age,sex){
    this.myName = name
    this.age = age
    this.sex = sex
    this.sayName = function (){

    }
}

// 父类型的原型对象中的方法也要继承,就是原型继承
Person.prototype.sayHi = function (){
    console.log('hello javascript')
}

Person.prototype.address = {
    city:'福州'
}

function Student(name,age,sex,score){
    Person.call(this,name,age,sex)
    this.score = score
}

Student.prototype = new Person()
// Student.prototype.constructor = Student

var s1 = new Student("zhangsan",23,"女",89)
var s2 = new Student("lisi",25,"男",90)
s1.address.city  = "南京"
console.dir(s1)
console.dir(s2)


</script>

image.png