JS构造函数新增属性/方法的两种方式

603 阅读1分钟

前言

本文给出了JS构造函数新增属性/方法的两种方式,如果对讲解有不一样见解的同学欢迎评论区补充讨论,当然有问题,也欢迎在评论区指出。

切记:这是学习js继承的基础,最好了解一下,才能解决这个大的模块

  • 继承----->后续更新

学习就是这么简单,你听懂了吗?

image.png

一、构造函数中定义属性/方法

function Father(name){
    this.name = name;
    this.play = function(){
        console.log('111')
    }
}
let father1 = new Father('hzy1')
let father2 = new Father('hzy2')
console.log(father1.name) //hzy1
console.log(father2.name) //hzy2

总结:构造函数内定义的属性/方法,实例是不可以共享构造函数中的属性/方法

二、通过原型链的方式定义构造函数的属性/方法

正确使用原型链方式定义新属性/方法

构造函数 . prototype . 方法/属性 = function() {};

function Father(name){
    this.name = name;
    this.play = function(){
        console.log('111')
    }
}
​
Father.prototype.say1 = function (){console.log('222')}
Father.prototype.say2 = function (){console.log('333')}
​
let father = new Father('hzy1')
console.log(father.say1()) //222
console.log(father.say2()) //333

总结:所有实例都可以共享构造函数中原型对象的属性/方法

错误写法:

构造函数 . prototype = {方法/属性:function() {} };

function Father(name){
    this.name = name;
    this.play = function(){
        console.log('111')
    }
}
​
Father.prototype.say1 = function (){console.log('222')}
Father.prototype = {say2:function (){console.log('333')}}
​
let father = new Father('hzy1')
console.log(father.say2()) //333
console.log(father.say1()) //报错say1未定义

总结:后面通过此种方式定义的属性/方法,会覆盖之前通过原型链定义的其它属性/方法

总结

觉得写得好的,对你有帮助的,可以分享给身边人,知识越分享越多,千万不要吝啬呀

至于js继承相关,请关注我,整理好,分享给你们,我们一起学前端。