建立自己的JS对象
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<script. type="text/javascript">
// 这个函数将成为自建对象的方法
function myMethod(){
alert("myMethod is invoked!");
}
</script>
</head>
<body>
<h1> Example of creating a JavaScript. object directly</h1>
<script. type="text/javascript">
// 建立一个对象,和它的一些属性
personObj=new Object();
personObj.firstname="John";
personObj.lastname="Doe";
personObj.age=50;
personObj.eyecolor="blue";
document.write(personObj.firstname + " is " + personObj.age + " years old.")
// 添加一个方法
personObj.myMethod=myMethod;
// 调用这个方法
personObj.myMethod();
</script>
</body>
</html>
使用模板来建立JS对象
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<script. type="text/javascript">
function myMethod(name){
alert("myMethod is invoked! The name of the person is " + name);
}
</script>
</head>
<body>
<h1> Example of creating a JavaScript. object through a template</h1>
<script. type="text/javascript">
// 定义一个模板,其实这个模板是一个函数, 而属性值会以这样的方式初始化
function person(firstname,lastname,age,eyecolor){
this.firstname=firstname
this.lastname=lastname
this.age=age
this.eyecolor=eyecolor
}
// 创建对象
myFather=new person("John","Doe",50,"blue")
document.write(myFather.firstname + " is " + myFather.age + " years old.")
myFather.myMethod=myMethod;
myFather.myMethod(myFather.firstname);
</script>
</body>
</html>
但是如果要再创建一个对象的话要再定义一次模板. 汗...
引用js文件
如果把
function myMethod(name){
alert("myMethod is invoked! The name is " + name);
}
放进1.js文件中,注意这时候不需要<script>
那么在主文件中可以引用它
<script. language="JavaScript"
type="text/javascript"
src="myOwnJavaScript.js">
</script>