小议Function.apply() 之一------(函数的劫持与对象的复制)

(编辑:jimmy 日期: 2026/4/30 浏览:2)

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

见protpotype.js 的实现方法:

复制代码 代码如下:Object.extend = function(destination, source) { 
  for (property in source) { 
    destination[property] = source[property]; 
  } 
  return destination; 

除此以外,还有一种不太常见的方法:  Function.apply.

apply 方法能劫持(<<Ajax in Action 书中用到"劫持"一语,很生动啊)另外一个对象的方法,
继承另外一个对象的属性。
示范代码如下:
Apply示范代码 
复制代码 代码如下:<script> 

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("\n")) 
    } 


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) 
</script>  学生类本来不具备任何方法,但是在 Person.apply(this,arguments)  后,他就具备了 Person类的sayhello方法和
所有属性。  在 Print.apply(this,arguments) 后就自动得到了  show() 方法。


本文,作为抛砖引玉,只对 apply 的用法(在对象继承和函数劫持方面)做个小示范,其他更深入的应用要
靠大家慢慢去领会了。
一句话新闻
高通与谷歌联手!首款骁龙PC优化Chrome浏览器发布
高通和谷歌日前宣布,推出首次面向搭载骁龙的Windows PC的优化版Chrome浏览器。
在对骁龙X Elite参考设计的初步测试中,全新的Chrome浏览器在Speedometer 2.1基准测试中实现了显著的性能提升。
预计在2024年年中之前,搭载骁龙X Elite计算平台的PC将面世。该浏览器的提前问世,有助于骁龙PC问世就获得满血表现。
谷歌高级副总裁Hiroshi Lockheimer表示,此次与高通的合作将有助于确保Chrome用户在当前ARM兼容的PC上获得最佳的浏览体验。