Home  >  Article  >  Web Front-end  >  Detailed explanation of JavaScript prototypal inheritance and combined inheritance code examples

Detailed explanation of JavaScript prototypal inheritance and combined inheritance code examples

伊谢尔伦
伊谢尔伦Original
2017-07-20 16:26:231401browse

Prototype:


##

function Body(name,age){// 创建一个Body类
  this.name = name;// 赋予基础属性name、age
  this.age = age;
}
Body.prototype.sayName =function() {// 给原型定义一个sayName的方法
  console.log(this.name);
}
var a = new Body('wutao','10');//创建一个Body的实例对象

function Another(){}
Another.prototype = new Body('www');//将Body实例对象给新创建的子类(Another)的prototype属性,这样,Another就拥有了Body的属性和方法
var b = new Another();//创建Another子类的实例
Another.prototype.sex ="mail";//定义子类的属性及方法
Another.prototype.saySex = function(){
  console.log(this.sex);
}
a.sayName();//wutao
b.sayName();//www 实例b拥有父类Body的方法sayName
b.saySex();//mail 实例b拥有自己定义的方法saySex

Borrowing the constructor (call&apply) can also be understood as combined inheritance call:

##

function Person(name){
  this.name = name;
  this.sayHello = function(){
    console.log(this.name);
  }
}

function Son(name,age){
  Person.call(this,name,age);//call用法:将this指针指向父类构造函数,并依次传入参数,使其拥有父类的属性和方法
  this.age = age;
  this.sayFunc = function(){
    console.log(this.name+"-"+this.age);
  } 
}
var a = new Person('wutao');
var b = new Son("wwwwww",22);
a.sayHello();//wutao
b.sayHello();//wwwwww; 通过call继承来的父类Person的方法sayHello
b.sayFunc();//wwwwww-22

apply:


function Person(name){
  this.name = name;
  this.sayHello = function(){
    console.log(this.name);
  }
}

function Son(name,age){
  Person.apply(this,[name,age]);//apply用法:类似call,将this指针指向父类构造函数,并传入一个由参数组成的数组参数,使其拥有父类的属性和方法
  this.age = age;
  this.sayFunc = function(){
    console.log(this.name+"-"+this.age);
  } 
}
var a = new Person('wutao');
var b = new Son("ttt",222);
a.sayHello();//wutao
b.sayHello();//ttt;通过apply继承来的父类Person的方法sayHello
b.sayFunc();//ttt-222

There are only these two main inheritance methods in js. Of course, there are several inheritance methods. However, in some inheritance methods, after creating an instance, modifying the instance methods and properties will directly modify the prototype methods and properties. In this case Inheritance seems to be of little significance, and it will only be used unless the business has similar needs.

The above is the detailed content of Detailed explanation of JavaScript prototypal inheritance and combined inheritance code examples. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn