The principle of JavaScript inheritance

Source: Internet
Author: User
Tags inheritance

Through the analysis of several functions of JavaScript, the conclusion is drawn:

JavaScript inheritance is actually modeled by initializing an object.

Code one: a way to implement inheritance

<script language="javascript" type="text/livescript">
function Person()
{
  this.say=function(){alert("Name")};
}
function PersonA()
{
  this.say=function(){alert("windowSay");};
}
PersonA();//对window对象添加方法
window.say();//显示windowSay
var Me={};
Person.call(Me);
Me.say();//输出结果为Name,可以得出Me通过Person.call(Me)“继承”了say方法
</script>
Contrast:

<script language="javascript" type="text/livescript">
function Person()
{
  
}
Person.say=function(){alert("Name")};
var Me={};
Person.call(Me);
//Me.say();//输出object doesn't support this method or property!我们可以看到Me并没有“继承”Person的say方法
</script>

Why, then?

The reason is that when the first method executes Person.call (Me), specify this as me in the person, and then execute the code in the person method

Obviously, This.say=function () {alert ("Name")}; This sentence adds a method to me. Let me object have a say behavior.

And when Persona (), to execute the code inside the persona, the This object represents window, so the window obtains the say behavior.

The second method executes the code inside the person, so it doesn't add behavior to me, and calling Me.say () is a natural error.

So it seems that by Call,apply,for (property in object), prototype and other methods to implement inheritance, only a simulated inherited

Way. The specific process is to dynamically add functions to an object, attributes.

Person.call (Me) is the property method that adds a person to Me, which function person () {alert ("Name");} Who is the object of the face?

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.