Discussing one of Function. apply () -- (Hijacking Function and copying object)

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.