The general method of Object Inheritance is to use the copy method: Object. extend.
See the implementation method of protpotype. js:
Copy codeThe 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 (<Ajax in Action> the book uses the phrase "hijack", which is very vivid) another object method,
Inherits the attributes of another object.
The Demo code is as follows:
Apply DEMO codeCopy codeThe 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.