1.創建對象
function createPerson(name, age) {
var person = new Object();
person.name = name;
person.age = age;
person.sayName = function () {
alert(this.name);
}
return person;
}
function Person(name, age) {
this.name = name;
this.age = age;
this.sayName = function () {
alert(this.name);
}
}
function prototype() {
function Person() {
}
Person.prototype = {
constructor: Person,
name: "json",
age: 23,
sayName: function () {
alert(this.name);
}
};
var p1 = new Person();
p1.sayName();
}
function standard() {
function Person(name, age) {
this.name = name;
this.age = age;
this.friends = ["kitty", "jack"];
}
Person.prototype = {
constructor: Person,
sayName: function () {
alert(this.name);
}
};
var p1 = new Person("jack", 11);
var p2 = new Person("rose", 22);
p1.friends.push("hhh");
alert(p1.friends);
alert(p2.friends);
}
2.繼承
function prototype() {
function SuperType() {
this.property = true;
}
SuperType.prototype.getSuperValue = function () {
return this.property;
}
function SubType() {
this.subproperty = false;
}
SubType.prototype = new SuperType();
SubType.prototype.getSubValue = function () {
return this.subproperty;
}
var instance = new SubType();
alert(instance.getSuperValue());
alert(instance.getSubValue());
}
function constructureStealing() {
function SuperType() {
this.colors = ["red", "blue"];
}
function SubType() {
SuperType.call(this);
}
var instance = new SubType();
instance.colors.push("green");
alert(instance.colors);
var instance2 = new SubType();
alert(instance2.colors);
}
function mix() {
function SuperType(name) {
this.name = name;
this.colors = ["red", "blue"];
}
SuperType.prototype.sayName = function () {
alert(this.name);
}
function SubType(name, age) {
SuperType.call(this, name);
this.age = age;
}
SubType.prototype = new SuperType();
SubType.prototype.constructor = SubType;
SubType.prototype.sayAge = function () {
alert(this.age);
}
var instance = new SubType("jack", 29);
instance.colors.push("green");
alert(instance.colors);
instance.sayName();
instance.sayAge();
var instance2 = new SubType("rose", 20);
alert(instance2.colors);
instance2.sayName();
instance2.sayAge();
}