当前位置:主页 > 网页前端 > JavaScript代码 >

nullJavascript中创建对象的五种方法实例

时间:2022-06-10 08:27:37 | 栏目: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>

您可能感兴趣的文章:

相关文章