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?