javascript中的类,继承,构造函数详解

 更新时间:2022年02月28日 11:35:09   作者:霜叶w  
这篇文章主要为大家详细介绍了javascript中的类,继承,构造函数,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能够给你带来帮助

前言

在es5中实现一个构造函数,并用new调用,即可得到一个类的实例。到了es6发布了Class的写法,js的面向对象变成也变得比较规范了。聊到类就不能不说类的构造函数以及类如何继承

一、Class类

定义一个类:

    class A {
        constructor(name){
            this.name = name
        }
        getName(){
            return this.name
        }
    }
    var newA = new A("A")
    console.log(newA.getName())  // A

二、es5构造函数

在es5中没有Class的写法,想要实现一个类的写法是这样的:

    class A {
        constructor(name){
            this.name = name
        }
        getName(){
            return this.name
        }
    }
    var newA = new A("A")
    console.log(newA.getName())  // A

三、实例、类的关系

实例的原型指向类的原型

console.log(newA.__proto__ === A.prototype)  // true

关于这个可以了解一下实例化的过程究竟发生了什么,查看MDN的连接:new操作符

  • 创建一个空的简单JavaScript对象(即{});
  • 为步骤1新创建的对象添加属性__proto__,将该属性链接至构造函数的原型对象 ;
  • 将步骤1新创建的对象作为this的上下文 ;
  • 如果该函数没有返回对象,则返回this。

Constructor

    console.log(A.prototype.constructor) // Class A

所有的对象都会从原型上继承一个constructor属性,是对函数本身的引用,也就是说指向函数本身。

这里实例newA的原型与A的原型相等,两者的原型的constuctor又都指向A本身。

需要注意的是constrctor是可以被修改的:参照MDN官方实例:constructor

function Type() { };

var	types = [
	new Array,
    [],
	new Boolean,
    true,        // remains unchanged
	new Date,
	new Error,
	new Function,
	function(){},
	Math,
	new Number,
	1,           // remains unchanged
	new Object,
	{},
	new RegExp,
	/(?:)/,
	new String,
	"test"       // remains unchanged
];

for(var i = 0; i < types.length; i++) {
	types[i].constructor = Type;
	types[i] = [ types[i].constructor, types[i] instanceof Type, types[i].toString() ];
};

console.log( types.join("\n") );

只有,true、1、“test”这种只读的原生结构不可被修改constuctor

四、继承

es6继承

    class Father{
        constructor(name){
            this.name = name
        }
    }
    class Son extends Father{
        constructor(name,sname){
            super(name)
            this.sname = sname
        }
        getSon(){
            return this
        }
    }
    var newSon = new Son("f","s")
    console.log(newSon.getSon())  // Son {name: 'f', sname: 's'}

es5继承的实现

    // 寄生组合继承
    function Sub(name){
        // 优先执行this绑定,以免覆盖子类的构造的值
        // 这里还有一个作用是拷贝了父类属性,避免所有子类共享引用属性!!!!
        Person.call(this)
        this.name = name || 's'
    }
    // 复制一份父类的原型,避免修改原型影响其他实例
    var fn = function(){}
    fn.prototype = Person.prototype
    Sub.prototype = new fn()
    var sub = new Sub('sub')
    sub.showName() 
    // user extend.html:19
    // my name is sub extend.html:21

关于继承详细的可以参考这篇:前端必知必会ES5、ES6的7种继承

总结

本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注脚本之家的更多内容!  

相关文章

最新评论