分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 代码编程

js 面向对象类

发布时间:2023-09-06 01:09责任编辑:傅花花关键词:js面向对象
  • 类的声明
  • 继承的几种方法

类的声明

第一种

function car(){ ???this.name = ‘name‘; ?}

第二种。es6中新添加的

class car(){ ?????constructor(){ ???????????this.name =‘name‘; ???}} ???

继承的几种方法

1.构造函数实现继承

function Parent(){ ???this.name = ‘parent‘;}Parent.prototype.toSay = function(){ ???console.log(this.name); ?}function Child(){ ???Parent.call(this); ???this.name1 = ‘child‘;}

console.log(new Child())

原理:在子类中调用了父级的构造函数,并把上下文换成子类,只是部分继承

缺点:看到上面输出的就知道,父类的prototype上的方法继承不了

2、原型链继承

上面的方法父类的prototype的方法继承不了,就自然会想到把父类实例赋值给子类的prototype这样,因为Parent的实例的__proto__指向了Parent.prototype

function Parent(){ ???this.name=‘parent‘;
   this.play = [1, 2, 3];}function Child(){ ???this.type="child";}Child.prototype = new Parent();var c1 = new Child();var c2= new Child();

  c2.play.push(4);
  console.log(c1.play, c2.play);

缺点:会改变原型链上的数值 

优化组合方法一

function Parent(){ ???this.name= ‘name‘; ???this.play = [1, 2, 3];}function Child(){ ???Parent.call(this); ???this.type = ‘child‘}Child.prototype = new Parent()var c1= new Child();var c2 = new Child();c2.play.push(4);console.log(c1.play, c2.play);

原理:这是上面两种方法的组合

缺点:父级的构造函数在子类实例的时候执行了两次

优化组合方法二

 function Parent () { ?????????this.name = ‘parent‘; ?????????this.play = [1, 2, 3]; ?????} ?????function Child () { ?????????Parent.call(this); ?????????this.type = ‘child‘; ?????} ?????Child.prototype = Parent.prototype; ?????var c1 = new Child(); ?????var c2 = new Child(); ?????console.log(c1 instanceof Child, c2 instanceof Parent); ?????console.log(c1.constructor);

原理:和上面的一种比较是不再实例Parent而是直接将Child.prototype指向Parent.prototype,这样parent原型链上有的方法,child也会有

缺点:子类的构造器是父类,而不是子类,因为他们共用了一个原型对象

完美的方法

function Parent(){ ???this.name = ‘parent‘; ???this.play=[1,2]}function Child(){ ???Parent.call(this) ???this.type = ‘child‘}Child.prototype = Object.create(Parent.prototype)Child.constructor = Child;

js 面向对象类

原文地址:http://www.cnblogs.com/myzy/p/7491079.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved