Implement object inheritance in javascript using the apply method

  • 2020-03-30 00:55:06
  • OfStack

 
<script type="text/javascript"> 
//Implement object inheritance using the apply method

function Parent(username) { 
this.username = username; 
this.sayHello = function() { 
alert(this.username); 
} 
} 

function Child(username, password) { 
Parent.apply(this, new Array(username)); 
//The same as below
//Parent.apply(this, [username]); 

this.password = password; 

this.sayWorld = function() { 
alert(this.password); 
} 
} 
var parent = new Parent("zhangsan"); 
var child = new Child("lisi", "123"); 

parent.sayHello(); 
child.sayHello(); 
child.sayWorld(); 

</script> 

Related articles: