关于javascript:js原型链继承和class继承

40次阅读

共计 1458 个字符,预计需要花费 4 分钟才能阅读完成。

class 继承

class People {constructor(name, age) {
        this.name = name
        this.age = age
    }
    eat() {console.log('I can eat')
    }
}

class Student extends People{constructor(name, age, xuehao) {super(name, age)
        this.xuehao = xuehao
    }
    read() {console.log('I read')
    }
}

const xiaoming = new Student('小明', 16, 8888)
console.log(xiaoming)
xiaoming.eat()  // I can eat
xiaoming.read() // I read

原型链继承

function People(name, age) {if (name) this.name = name
    if (age) this.age = age
}

People.prototype.eat = function() {console.log('I can Eat')
}

function Student(name, age, xuehao) {People.call(this, name, age)
    this.xuehao = xuehao
}

/**
 * 通过将构造函数(Student)的原型(prototype)指向另一个对象(People)的实例,* 这是实现原型链继承的最佳技术计划。*  */ 

Student.prototype = new People()
/**
 * 然而这样做了之后,Student.prototype.constructor 的值就变了,不再是 Student 了。* 所以须要通过 Object.defineProperty 办法将 Student.prototype 上的 constructor 再改成 Student。* 其实,当 Student.prototype = new People() 执行后,Student.prototype 是 People 的一个实例,* Student.prototype 自身没有 constructor 属性,Student.prototype.constructor 其实会去原型链下来找,也就是:* Student.prototype.constructor 
 * === Student.prototype.__proto__.constructor 
 * === People.prototype.construcctor === People
 * (实例的隐式原型__proto__等于其构造函数的显式原型 prototype,所以有 Student.prototype.__proto__ === People.prototype)
 * (而构造函数 People 的显式原型属性 prototype 上的 constructor 指向自身,所以有 People.prototype.construcctor === People)
 */
Object.defineProperty(Student.prototype, 'constructor', {
    enumerable: false,
    value: Student,
    writable: true
})

Student.prototype.read2 = function() {console.log('I read')
}

const xialuo = new Student('着落', 17, 6666)
console.log(xialuo)
xialuo.eat()  // I can eat
xialuo.read2() // I read

正文完
 0