A brief discussion on one of the function.apply ()------(function hijacking and object duplication) _javascript skills

Source: Internet
Author: User
Tags extend inheritance
On the inheritance of objects, the general practice is to use the Copy method: Object.extend

See Protpotype.js Implementation method:

Copy Code code 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 (<<ajax in action>> book use "hijack" a language, very vivid AH) Another object of the method,
Inherits the properties of another object.
The model code is as follows:
Apply Demo Code
Copy Code code 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 () {//Show properties of Class
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", 13, 6, "Tsinghua Primary School")
S1.show ()
S1.sayhello ()
Alert (S1.funcname)
</script>
The student class does not have any method, but after person.apply (this,arguments), he has the SayHello method of the person class and
All properties. The show () method is automatically obtained after print.apply (this,arguments).


This article, as a trigger, only on the use of application (in object inheritance and function hijacking aspects) to do a small demonstration, other more in-depth applications to
It's up to 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.