Discussing Function. apply () ------ (Function hijacking and object replication) _ javascript skills

Source: Internet
Author: User
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.

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.