继承

1.如何通过原型链实现继承?

基本思想:让一个引用类型继承另一个引用类型的属性和方法。
回顾:每个构造函数都有一个原型对象,原型对象都包含一个指向构造函数的指针,而实例都包含一个指向原型对象的内部指针。

注意:不能使用对象字面量创建原型方法。

 2.原型链的问题?

问题一:原型的实例属性会变成原型属性。

问题二:创建子类型的实例时,不能向超类型的构造函数中传递参数。

3.借用构造函数?

基本思想:在子类型构造函数的内部调用超类型构造函数。

回顾:构造函数就是初始化一个实例对象,对象的prototype属性是继承一个实例对象。

function Person( name){
        this.name =name;
      }
var p1=new Person('John');
View Code

优势:可以在子类型构造函数中向超类型构造函数中传递参数

function SuperType(name){
    this.name = name;
}

function SubType(){
  //继承,传递参数 SuperType.call(
this,"Nicholas");

  //实例属性
this.age = 29; } var instance = new SubType(); alert(instance.name); alert(instance.age);

问题:不可以函数复用

另外:call()函数:

 add.call(sub,3,1);  
这个例子中的意思就是用 add 来替换 sub,add.call(sub,3,1) == add(3,1) ,所以运行结果为:alert(4); // 注意:js 中的函数其实是对象,函数名是对 Function 对象的引用。

4.组合继承?

既可以让两个不同观点SubType实例分别拥有自己的属性,又可以使用相同的方法。

function SuperType(name){
    this.name = name;
    this.colors=["red","blue","green"];
}

SuperType.prototype.sayName = function(){
    alert(this.name);
};

function SubType(name,age){
    SuperType.call(this,name);//继承

    this.age = age;
}

SubType.prototype = new SuperType();
SubType.prototype.constructor=SubType;
SubType.prototype.SayAge = function(){
    alert(this.age);
};

var instance1 = new SubType("Nicholas",29);
instance1.colors.push("black");
alert(instance1.colors);
instance1.sayName();
instance1.SayAge();

var instance2 = new SubType("Greg",23);
alert(instance2.colors);
instance2.sayName();
instance2.SayAge();

 5.原型式继承

基本思路:借助原型可以基于已有的对象创建新对象,同时还不必因此创建自定义类型。

var person={
    name:"Nicholas",
    friends:["shelby","court","van"]
};

//继承
var anotherPerson = Object.create(person,{
    name:{value:"Greg"}//继承属性
})

alert(anotherPerson.name);

有一个公式一般的函数:

原文地址:https://www.cnblogs.com/n2meetu/p/6752206.html