Home >Web Front-end >JS Tutorial >A brief discussion on Function.apply() Part 1------(Function hijacking and object copying)_javascript skills

A brief discussion on Function.apply() Part 1------(Function hijacking and object copying)_javascript skills

WBOY
WBOYOriginal
2016-05-16 19:23:391351browse

Regarding the inheritance of objects, the general approach is to use the copy method: Object.extend

See the implementation method of protpotype.js:

Copy code The code is as follows:
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
Copy code The code is as follows:
< 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.
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn