SoFunction
Updated on 2025-03-01

JS object inheritance example

This article describes the usage of prototype chain inheritance of js object inheritance. Share it for your reference. The specific analysis is as follows:

Copy the codeThe code is as follows:
<script type="text/javascript">
//Define the object of the cat
var kitty  = {color:'yellow',bark:function(){alert('meow');},climb:function(){alert('I can climb trees')}};

//Tiger object constructor
function tiger(){
  = "yellow and black";
  = function(){
alert('Hohaha...');
 }
}

//Declare the prototype to the constructor, then the constructed object will have an ancestor: that is, the prototype
= kitty;
//or = new kitty();//If kitty is function, this method is used

var t = new tiger();
();
();//When calling the tiger's properties or methods, first look for its constructor; if not, go to the prototype of the tiger constructor. But be aware that here it does not copy the climb() method in the prototype object to itself. This is prototype chain search.
</script>


Other notes: kitty also has a constructor, that is, new Object(). Object also has some methods and properties by default, see "object object" in the javascript manual. At the same time, it also has a prototype, just empty { }.

I hope this article will be helpful to everyone's JavaScript programming.