javaScript 常见构造方法继承方法

原文链接https://www.cnblogs.com/zczhangcui/p/6389023.html

 

一、构造方法

1、工厂模式

  考虑在ES中无法创建类(ES6前),开发人员发明了一种函数,用函数来封装以特定接口创建对象的细节。(实现起来是在一个函数内创建好对象,然后把对象返回)。

function createPerson(name,age,job){
    var o=new Object();
    o.name=name;
    o.age=age;
    o.job=job;
    o.sayName=function(){
        alert(this.name);
    };
    return o;
}

var person1=createPerson("Nicholas",29,"Software Engineer");
var person2=createPerson("Greg",27,"Doctor");
函数createPerson()能够根据接受参数来构建一个包含所有必要信息的Person对象。
工厂模式虽然解决了创建多个相似对象的问题,但却没有解决对象识别的问题,即怎么知道一个对象的类型

2、构造函数模式

  像Object和Array这样的原生构造函数,在运行时会自动出现在执行环境。此外,也可以创建自定义的构造函数,从而定义自定义对象类型的属性和方法。

function Person(name,age,job){
    this.name=name;
    this.age=age;
    this.job=job;
    this.sayName=function(){
        alert(this.name);
    };
}

var person1=new Person(...);
var person2=new Person(...);

  与工厂模式相比,具有以下特点:

  1. 没有显式创建对象;
  2. 直接将属性和方法赋给了this对象;
  3. 没有return语句;
  4. 要创建新实例,必须使用new操作符;(否则属性和方法将会被添加到window对象)
  5. 可以使用instanceof操作符检测对象类型

  构造函数的问题:

  构造函数内部的方法会被重复创建,不同实例内的同名函数是不相等的。可通过将方法移到构造函数外部解决这一问题,但面临新问题:封装性不好。

3、原型模式

  我们创建的每个函数都有一个prototype属性,这个属性是一个指针,指向一个对象,而这个对象的用途是包含可以由特定类型的所有实例共享的属性和方法。(prototype就是通过调用构造函数而创建的那个对象实例的原型对象)。

  使用原型对象的好处是可以让所有对象实例共享它所包含的属性和方法。换句话说,不必在构造函数中定义对象实例的信息,而是可以将这些信息直接添加到原型对象中。

function Person(){
}

Person.prototype.name="Nicholas";
Person.prototype.age=29;
Person.prototype.job="...";
Person.prototype.sayName=function(){
    ...
};

var person1=new Person();
person1.sayName();//"Nicholas"

  更常见的做法是用一个包含所有属性和方法的对象字面量来重写整个原型对象,并重设constructor属性。

function Person(){
}

Person.prototype={
    name:"...",
    age:29,
    job:"...",
    sayName:function(){
        ...
    }
};

Object.defineProperty(Person.prototype,"constructor",{
    enumerable:false,
    value:Person,
});
原型对象的问题:
  1. 他省略了为构造函数传递初始化参数这一环节,结果所有实例在默认情况下都将取得相同的属性值,虽然这会在一定程度带来一定的不便,但不是最大的问题,最大的问题是由其共享的本性所决定的。
  2. 对于包含基本值的属性可以通过在实例上添加一个同名属性隐藏原型中的属性。然后,对于包含引用数据类型的值来说,会导致问题。

 这些问题导致很少单独使用原型模式。

4、组合使用构造函数模式和原型模式

  这是创建自定义类型的最常见的方式。

  构造函数模式用于定义实例属性,而原型模式用于定义方法和共享的属性。所以每个实例都会有自己的一份实例属性的副本,但同时共享着对方法的引用,最大限度的节省了内存。同时支持向构造函数传递参数。

function Person(name,age,job){
    this.name=name;
    this.age=age;
    this.job=job;
    this.friends=["S","C"];
}

Person.prototype={
    constructor:Person,
    sayName:function(){
        alert(this.name);
    }
};

var person1=new Person(...);

5、动态原型模式

function Person(name,age,job){
    this.name=name;
    this.age=age;
    this.job=job;

    if(typeof this.sayName!="function"){
        Person.prototype.sayName=function(){
            alert(this.name);
        };
    }
}

  这里只有sayName()不存在的情况下,才会将它添加到原型中,这段代码只会在初次调用构造函数时才执行。这里对原型所做的修改,能够立刻在所有实例中得到反映。

原文链接https://www.cnblogs.com/lanyueff/p/7792009.html

二、继承

1.原型链继承

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

function Parent () {

  this.name = 'kevin';

}

 

Parent.prototype.getName = function () {

  console.log(this.name);

}

//组合使用构造函数模式和原型模式

function Child () {

 

}

Child.prototype = new Parent();

 

var child1 = new Child();

 

console.log(child1.getName()) // kevin

问题:

1.引用类型的属性被所有实例共享,举个例子:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

function Parent () {

  this.names = ['kevin''daisy'];

}

function Child () {

 

}

 

Child.prototype = new Parent();

 

var child1 = new Child();

 

child1.names.push('yayu');

 

console.log(child1.names); // ["kevin", "daisy", "yayu"]

 

var child2 = new Child();

 

console.log(child2.names); // ["kevin", "daisy", "yayu"]

2.在创建 Child 的实例时,不能向Parent传参

2.借用构造函数(经典继承)

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

function Parent () {

  this.names = ['kevin''daisy'];

}

 

function Child () {

  Parent.call(this);

}

 

var child1 = new Child();

 

child1.names.push('yayu');

 

console.log(child1.names); // ["kevin", "daisy", "yayu"]

 

var child2 = new Child();

 

console.log(child2.names); // ["kevin", "daisy"]

优点:

1.避免了引用类型的属性被所有实例共享

2.可以在 Child 中向 Parent 传参

举个例子:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

function Parent (name) {

  this.name = name;

}

 

function Child (name) {

  Parent.call(this, name);

}

 

var child1 = new Child('kevin');

 

console.log(child1.name); // kevin

 

var child2 = new Child('daisy');

 

console.log(child2.name); // daisy

缺点:

方法都在构造函数中定义,每次创建实例都会创建一遍方法。

3.组合继承

原型链继承和经典继承双剑合璧。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

function Parent (name) {

  this.name = name;

  this.colors = ['red''blue''green'];

}

 

Parent.prototype.getName = function () {

  console.log(this.name)

}

 

function Child (name, age) {

 

  Parent.call(this, name);

   

  this.age = age;

 

}

 

Child.prototype = new Parent();

Child.prototype.constructor=Child;

 

var child1 = new Child('kevin''18');

 

child1.colors.push('black');

 

console.log(child1.name); // kevin

console.log(child1.age); // 18

console.log(child1.colors); // ["red", "blue", "green", "black"]

 

var child2 = new Child('daisy''20');

 

console.log(child2.name); // daisy

console.log(child2.age); // 20

console.log(child2.colors); // ["red", "blue", "green"]

优点:融合原型链继承和构造函数的优点,是 JavaScript 中最常用的继承模式。

4.原型式继承

1

2

3

4

5

function createObj(o) {

  function F(){}

  F.prototype = o;

  return new F();

}

就是 ES5 Object.create 的模拟实现,将传入的对象作为创建的对象的原型。

缺点:

包含引用类型的属性值始终都会共享相应的值,这点跟原型链继承一样。

1

2

3

4

5

6

7

8

9

10

11

12

13

var person = {

  name: 'kevin',

  friends: ['daisy''kelly']

}

 

var person1 = createObj(person);

var person2 = createObj(person);

 

person1.name = 'person1';

console.log(person2.name); // kevin

 

person1.firends.push('taylor');

console.log(person2.friends); // ["daisy", "kelly", "taylor"]

注意:修改person1.name的值,person2.name的值并未发生改变,并不是因为person1person2有独立的 name 值,而是因为person1.name = 'person1',给person1添加了 name 值,并非修改了原型上的 name 值。

5. 寄生式继承

创建一个仅用于封装继承过程的函数,该函数在内部以某种形式来做增强对象,最后返回对象。

1

2

3

4

5

6

7

function createObj (o) {

  var clone = object.create(o);

  clone.sayName = function () {

    console.log('hi');

  }

  return clone;

}

缺点:跟借用构造函数模式一样,每次创建对象都会创建一遍方法。

6. 寄生组合式继承

为了方便大家阅读,在这里重复一下组合继承的代码:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

function Parent (name) {

  this.name = name;

  this.colors = ['red''blue''green'];

}

 

Parent.prototype.getName = function () {

  console.log(this.name)

}

 

function Child (name, age) {

  Parent.call(this, name);

  this.age = age;

}

 

Child.prototype = new Parent();

 

var child1 = new Child('kevin''18');

 

console.log(child1)

组合继承最大的缺点是会调用两次父构造函数。

一次是设置子类型实例的原型的时候:

1

Child.prototype = new Parent();

一次在创建子类型实例的时候:

1

var child1 = new Child('kevin''18');

回想下 new 的模拟实现,其实在这句中,我们会执行:

1

Parent.call(this, name);

在这里,我们又会调用了一次 Parent 构造函数。

如果我们打印 child1 对象,我们会发现 Child.prototype 和 child1 都有一个属性为colors,属性值为['red', 'blue', 'green']。

那么我们该如何精益求精,避免这一次重复调用呢?

如果我们不使用 Child.prototype = new Parent() ,而是间接的让 Child.prototype 访问到 Parent.prototype 呢?

看看如何实现:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

 

function Parent (name) {

  this.name = name;

  this.colors = ['red''blue''green'];

}

 

Parent.prototype.getName = function () {

  console.log(this.name)

}

function Child (name, age) {

  Parent.call(this, name);

  this.age = age;

}

// 关键的三步

var F = function () {};

 

F.prototype = Parent.prototype;

 

Child.prototype = new F();

 

 

var child1 = new Child('kevin''18');

 

console.log(child1);

最后我们封装一下这个继承方法:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

function object(o) {

  function F() {}

  F.prototype = o;

  return new F();

}

 

function prototype(child, parent) {

  var prototype = object(parent.prototype);

  prototype.constructor = child;

  child.prototype = prototype;

}

 

// 当我们使用的时候:

prototype(Child, Parent);

对寄生组合式继承的夸赞就是:

这种方式的高效率体现它只调用了一次Parent构造函数,并且因此避免了在 Parent.prototype 上面创建不必要的、多余的属性。与此同时,原型链还能保持不变;因此,还能够正常使用 instanceof 和 isPrototypeOf。开发人员普遍认为寄生组合式继承是引用类型最理想的继承范式。

 

 

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值