当前位置: 首页 > 图文教程 > 网络编程 > Javascript > 小议Function.apply() 之一------(函数的劫持与对象的复制)

Javascript
Add a Table to a Word Document
Add Formatted Text to a Word Document
用jscript实现新建word文档
用jscript实现新建和保存一个word文档
Open and Print a Word Document
Use Word to Search for Files
Convert Seconds To Hours
Sample script that deletes a SQL Server database
Sample script that displays all of the users in a given SQL Server DB
firefox中用javascript实现鼠标位置的定位
div+css实现鼠标放上去,背景跟图片都会变化。
Locate a File Using a File Open Dialog Box
Save a File Using a File Save Dialog Box
用jscript实现列出安装的软件列表
List the Stored Procedures in a SQL Server database
Display SQL Server Login Mode
Display SQL Server Version Information
List all the Databases on a SQL Server
用jscript启动sqlserver
Stop SQL Server

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


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-12   浏览: 190 ::
收藏到网摘: n/a

关于对象的继承,一般的做法是用复制法: 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 的用法(在对象继承和函数劫持方面)做个小示范,其他更深入的应用要
靠大家慢慢去领会了。