码迷,mamicode.com
首页 > Web开发 > 详细

js 面向对象类

时间:2017-09-07 19:26:58      阅读:187      评论:0      收藏:0      [点我收藏+]

标签:div   var   function   类的声明   com   style   eof   上下   赋值   

  • 类的声明
  • 继承的几种方法

 

类的声明

第一种

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 面向对象类

标签:div   var   function   类的声明   com   style   eof   上下   赋值   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!