DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> 關於JavaScript >> nullJavascript中創建對象的五種方法實例
nullJavascript中創建對象的五種方法實例
編輯:關於JavaScript     

復制代碼 代碼如下:
<script type="text/javascript">

// 方法一
var p0 = new Object();
p0.name = "xy";
p0.age = 20;
p0.sayName = function() { alert(this.name); }
p0.showAgeAfterSomeYears = function(year) { return this.age + year };
p0.sayName();
alert(p0.showAgeAfterSomeYears(10));

// 方法二
function Person(){
}
var p1 = new Person();
p1.name = "xy";
p1.age = 20;
p1.sayName = function() { alert(this.name); }
p1.showAgeAfterSomeYears = function(year) { return this.age + year };
p1.sayName();
alert(p1.showAgeAfterSomeYears(10));

// 方法三
function Person(name,age){
this.name = name;
this.age = age;
this.sayName = function(){ alert(this.name); }
this.showAgeAfterSomeYears = function(year) { return this.age + year };
}
var p2 = new Person("xy",20);
p2.sayName();
alert(p2.showAgeAfterSomeYears(10));

// 方法四
var p3 = {
name : "xy",
age : 20,
sayName : function(){ alert(this.name); },
showAgeAfterSomeYears : function(year) { return this.age + year }
};
p3.sayName();
alert(p3.showAgeAfterSomeYears(10));

// 方法五
var p4 = {};
p4.name = "xy";
p4.age = 20;
p4.sayName = function() { alert(this.name); }
p4.showAgeAfterSomeYears = function(year) { return this.age + year };
p4.sayName();
alert(p4.showAgeAfterSomeYears(10));

</script>

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved