復制代碼 代碼如下:
<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>