//1.0.1 定义js对象的方式1
function c01DefineObj1() {
var obj = new Object();
obj.Name = "八戒";
obj.Age = 500;
obj.Say = function () {
//alert("Name=" + obj.Name + ", Age=" + obj.Age);
alert("Name=" + this.Name + ", Age=" + this.Age);
}
//执行obj中的Say方法
obj.Say();
}
-----------------------------------------------------------------------
//1.0.2 定义js对象的方式2,利用js对象的字面量表示形式
function DefineObj2() {
var obj2 =
{
Name: "唐僧",
Age: 1000,
Say: function () {
alert("name=" + this.Name + " ,Age=" + this.Age);
}
};
-------------------------------------------------------------------------
//1.0 创建对象(构造函数实例化)
function Person(name, age) {
var c = new Object();
c.name = name;
c.age = age;
c.sayName = function () { alert(this.name); };
return c;
}
//直接new函数Person()执行方法体,最终创建好对象,将指针返回给p1
var p1 = new Person("ivan", 29);
-------------------------------------------------------------------------------------------------------
//2.0 创建对象(原型模式)
function dog(name, age) {
this.name = name;
this.age = age;
//this.SayHi = function () {
// alert("name=" + this.name + ",age=" + this.age);
//}
}
//给dog原型属性上添加SayHi方法
dog.prototype.SayHi = function () {
alert("name=" + this.name + ",age=" + this.age);
}
var d1 = new dog("小黄", 2);
------------------------------------------------------------------------------------
//3.0 继承(寄生组合模式)
function Pig(name, age) {
this.name = name;
this.age = age;
//this.SayHi = function () {
// alert("name=" + this.name + " ,age=" + this.age);
//};
}
Pig.prototype.SayHi = function () {
alert("name=" + this.name + " ,age=" + this.age);
};
function smallPig(name, age) {
//将Pig方法中的this改成smallPig中的this
Pig.call(this, name, age);
}
//将Pig上的原型继承过来
smallPig.prototype = new Pig(); //将来在smallPig.prototype上添加新的属性或者方法的时候才不会影响到Pig的原型
smallPig.prototype.SayHi1 = function () { };
var p12 = new smallPig("小猪", 1);
p12.SayHi();
--------------------------------------------------------------------------------------------------------------------------
//4.0 创建对象(工厂模式)
function createPerson(name, age) {
var c = new Object();
c.name = name;
c.age = age;
c.sayName = function () { alert(this.name); };
return c;
}
var p1 = createPerson("ivan", 29);
p1.sayName();
var p2 = createPerson("james", 30);
p2.sayName();