网络编程
位置:首页>> 网络编程>> JavaScript>> javascript中的类,继承,构造函数详解

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

作者:霜叶w  发布时间:2024-07-30 01:08:53 

标签: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() { };

vartypes = [
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、&ldquo;test&rdquo;这种只读的原生结构不可被修改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种继承

来源:https://blog.csdn.net/weixin_44043130/article/details/123147416

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com