Regarding the inheritance of objects, the general approach is to use the copy method: Object.extend
See the implementation method of protpotype.js:
Object.extend = function(destination, source) {
for (property in source) {
destination[property] = source[property ];
}
return destination;
}
In addition, there is a less common method: Function.apply.
apply method can hijack ( <
> The word "hijacking" is used in the book, which is very vivid) The method of another object,
inherits the properties of another object.
The sample code is as follows:
Apply sample code
< script>
function Person(name,age){ //Define 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," ; name,age,grade,school){ //Student class
Person.apply(this,arguments)
Print.apply(this,arguments)
this.grade=grade //Grade
this .school=school tom",13,6,"Tsinghua Primary School")
s1.show()
s1.sayhello()
alert(s1.funcName)
Student class Originally it did not have any methods, but after Person.apply(this,arguments), it has the sayhello method of the Person class and all the attributes of
. After Print.apply(this,arguments), you automatically get the show() method.
This article, as an introduction, only gives a small demonstration of the usage of apply (in terms of object inheritance and function hijacking). Other more in-depth applications are
for everyone to understand slowly.