Javascript继承方式 发表于 2019-03-29 | 分类于 Javascript | | 字数统计: 427 字 | 阅读时长≈ 2 分钟 构造函数继承Parent: 父对象Child: 子对象 构造函数绑定123456789101112131415function Parent() { this.country = 'shanghai';}function Child(name, age) { // call 或者 apply // call([对象名], arg1, arg2, arg3, ...) 第一个是对象,后续参数是传入该函数的值 // apply([对象名], [arg1, arg2, arg3, ...]) 第一个是对象, 第二个是数组,这个数组就是该函数的参数(arguments) Parent.apply(this, arguments) this.name = name; this.age = age;}let child = new Child('jesse', 26)console.log(child.country) prototype模式12345678910111213141516function Parent() { this.country = 'shanghai';}function Child(name, age) { this.name = name; this.age = age;}let Child.prototype = new Parent()// 需手动指定Child的constructorChild.prototype.constructor = Childlet child = new Child('jesse', 26)console.log(Child.prototype.constructor == Parent)console.log(child.country) 直接继承prototype1234567891011function Parent() {}function Child() {}Parent.prototype.country = 'shanghai'Child.prototype = Parent.prototypeChild.prototype.constructor = Childlet child = new Child()console.log(child.country)// 会同时改变Parent.prototypeconsole.log(Parent.prototype.constructor == Child) 利用空对象12345678910111213function Parent() {}function Child() {}// 空对象let F = function() {}F.prototype = Parent.prototypeChild.prototype = new F()Child.prototype.constructor = Childlet child = new Child()console.log(child.country)console.log(Parent.prototype.constructor) 封装为方法: 12345678910111213141516function extend(C, P) { let F = function() {} F.prototype = P.prototype C.prototype = new F() C.prototype.constructor = C // 为子对象设一个uber属性,这个属性直接指向父对象的prototype属性,可以直接调用父对象的方法,为了实现继承的完备性,纯属备用性质 C.uber = P.prototype}function Parent() {}function Child() {}Parent.prototype.country = 'shanghai'extend(Child, Parent) 拷贝继承12345678910111213141516// 将父对象的prototype对象中的属性,--拷贝给Child对象的prototype对象function extend(C, P) { let p = P.prototype let c = C.prototype for (let k in p) { c[k] = p[k] } c.uber = p}function Parent() {}function Child() {}Parent.prototype.country = 'shanghai'extend(Child, Parent) 非构造函数继承待