面向对于javascript编程

时间:2022-01-23 06:56:34

以构造函数的方式定义对象

 function Person(name, age) {
this.name = name;
this.age = age;
this.sayName = function () {
alert(this.name);
}
} var person1 = new Person("wilson1", 10);
var person2 = new Person("wilson2",20); Person("wilson3", 30); person1.sayName();
person2.sayName(); window.sayName();

定义对象属性

  var person = { _name: "", age: 0, Name: "" };
Object.defineProperty(person, "name", {
get: function () {
return this._name;
},
set: function (newvalue) {
this._name = newvalue;
}
}); person.name = "wilson.fu";

原型式定义对象

var Person = function (age, name) {
this.age = age;
this.name = name;
}
Person.prototype.name = "";
Person.prototype.age = 0;
Person.prototype.sayName = function () {
alert(this.name);
}
//Person.prototype.name = "wilson"; var person1 = new Person(10, "wilson1");
person1.sayName(); var person2 = new Person(20, "wilson2"); person2.sayName();

构造函数与原型模式结合式声明对象

面向对于javascript编程

   var Person = function (age, name) {
this.age = age;
this.name = name;
}
//Person.prototype.name = "Old Value";
//Person.prototype.age = 0;
//Person.prototype.sayName = function () {
// alert(this.name);
//} Person.prototype = {
constructor:Person,
sayName: function () {
alert(this.name);
}
};

详见:http://www.cnblogs.com/weiweictgu/p/5658996.html