alianzhang / Personal-summary

这是我个人的代码知识块总结,备注比较多,方便理解,适合初学者参考借鉴
0 stars 0 forks source link

js原型链继承题 #1

Open alianzhang opened 5 years ago

alianzhang commented 5 years ago

分解代码执行过程并绘制图谱的网址

// 定义Person构造函数
function Person (name) {
    this.name = name
    this.sayHello = function(){
        console.log('hello')
    }
}
Person.prototype.sayName = function(){
    console.log(this.name)
}

// 定义Teacher构造函数
function Teacher (name,classT){
    Person.call(this,name)
    this.classT = classT
}
Teacher.prototype = Object.create(Person.prototype)
Teacher.prototype.constructor = Teacher
Teacher.prototype.sayClass = function(){
    console.log(this.classT)
}

// 定义MathTeacher构造函数
function MathTeacher(name,level){
    Teacher.call(this,name,'math')
    this.level = level
}
MathTeacher.prototype = Object.create(Teacher.prototype)
MathTeacher.prototype.constructor = MathTeacher
MathTeacher.prototype.sayLevel = function (){
    console.log(this.level)
}

let ZhangLaoshi = new MathTeacher('Zhang San','Great')
let WangLaoshi = new Teacher('Wang Wu','English')
let Lisi = new Person('Li Si')
alianzhang commented 5 years ago

原型链题:

function Parent(){
    this.a = 1
    this.b = [1,2,this.a]
    this.c = {demo:5}
    this.show = function (){
        console.log(this.a,this.b,this.c.demo)
    }
}
function Child(){
    this.a = 2
    this.change = function (){
        this.b.push(this.a)
        this.a = this.b.length
        this.c.demo = this.a++
    }
}
Child.prototype = new Parent()
var parent = new Parent()    
var child1 = new Child()
var child2 = new Child()
child1.a = 11
child2.a = 12
parent.show()
child1.show()
child2.show()
child1.change()
child2.change()
parent.show()
child1.show()
child2.show()
alianzhang commented 4 years ago

image