---
title: "javaScript apply方法 "
author: "butterflymacro"
date: "2009-07-28T20:24:01Z"
tags: []
slug: "javascript-apply"
draft: false
lastmod: "2009-07-28T20:24:01Z"
id: 434845
url: "https://butterflymacro.iteye.com/blog/434845"
---

函数的劫持与对象复制

关于对象的继承 ，一般做法是复制法: Object.extend

Prototype.js的实现方法如下：

 Object.extend = function(destination ,source){

   for (property in source){

        destination\[property] =source\[property];

}

    return destination;

}

除此之外，还有一种不太常见的方法：Function.apply

 apply方法能劫持另一个对象的方法来继承另一个对象的属性

Example：

&lt;script&gt;

   function Person(name,age){//定义一个类

        this.name =name

        this.age=age

        this.sayhello=function(){alert("hello")}

 

}

   function Print(){

   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(" "));

}

 function Student(name,age,grade,school){//学生类

   Person.apply(this,arguments)

   Print.apply(this,arguments)

   this.grade =grade

   this.school =school

}

var p1=new Person("jake",10)

    p1.sayhello()

var s1 = new Student("tom",13,6,"清华小学")

     s1.show()

    s1.sayhello()

    alert(s1.funcName)

&lt;/script&gt;

学生类本来不具备任何方法，但是在Person.apply(this,arguments)后，他就具备了Person类的sayhello方法和所有属性 在Print.apply(this,arguments)后就自动得到了show()方法