Discuss Function. apply () ------ (Function hijacking and Object replication) about Object inheritance, the general method is to use the copy method: Object. extend
See the implementation method of protpotype. js:
The code is as follows:
Object. extend = function (destination, source ){
For (property in source ){
Destination [property] = source [property];
}
Return destination;
}
In addition, there is also an uncommon method: Function. apply.
The apply method can hijack (<> the phrase "hijack" is used in the book, which is very vivid) the method of another object,
Inherits the attributes of another object.
The demo code is as follows:
Apply demo code
The code is as follows:
Script
Function Person (name, age) {// defines a class, Human
This. name = name // name
This. age = age // age
This. sayhello = function () {alert ("hello ")}
}
Function Print () {// Display class attributes
This. funcName = "Print"
This. show = function (){
Var msg = []
For (var key in this ){
If (typeof (this [key])! = "Function") msg. push ([key, ":", this [key]. join (""))
}
Alert (msg. join ("\ n "))
}
}
Function Student (name, age, grade, school) {// Student class
Person. apply (this, arguments)
Print. apply (this, arguments)
This. grade = grade // grade
This. school = school // school
}
Var p1 = new Person ("jake", 10)
P1.sayhello ()
Var s1 = new Student ("tom", "Tsinghua Primary School ")
S1.show ()
S1.sayhello ()
Alert (s1.funcName)
Script
The student class does not have any methods, but after Person. apply (this, arguments), he has the sayhello method and
All attributes. After Print. apply (this, arguments), the show () method is automatically obtained.
This article serves as an example to demonstrate only the usage of apply (in terms of object inheritance and function hijacking ).
It was easy for everyone to understand.