Javascript functions are objects with spcified property named apply. The apply method is used as the constructor of the object. The object is passed as the first parameter to the apply method. The second parameter is always an array used to initialize the object being passed with the array object.
A function named Person has three parameters and initialize the object property with the passed arguments. Here "this" refer to the object that invoke the apply method ie Aperson object. Aperson function applies Person attributes with itself as first argument and array as its parameters.
function Person(firstname,middlename,lastname)
{
this.firstname = firstname;
this.middlename= middlename;
this.lastname = lastname;
}
function Aperson(age, firstname, middlename, lastname)
{
this.age = age;
Person.apply(this, new Array(firstname, middlename, lastname))
}
aperson = new Aperson(31,"Bill","Jill","King")
console.log(aperson.firstname + " " + aperson.middlename + " " + aperson.lastname + " is " + aperson.age +" years old.") ;
Output
Bill Jill King is 31 years old.
No comments:
Post a Comment