关闭

javascript对象的几种方式

195人阅读 评论(0) 收藏 举报

一)基于已有对象扩充其属性和方法

var student = new Object();
student.name = "Chris";
student.sayName = function(name) {
    this.name = name;
    alert(this.name);
};

二)工厂方式

function getInfo() {
    alert(this.name + "," + this.age);
}

function CreateObj() {
    var obj = new Object();
    obj.name = "Chris";
    obj.age = 23;
    obj.getInfo = getInfo;
    return obj;
}

var obj1 = new CreateObj();
var obj2 = new CreateObj();

三)构造函数方式

function Student(name, age) {
    this.name = name;
    this.age = age;
    this.getInfo = function () {
        alert(this.name + "," + this.age);
    };
}

var stu = new Student("Chris", 23);
stu.getInfo();

四)原型(prototype)方式

function Student() {
}

Student.prototype.name = "Chris";
Student.prototype.age = 23;
Student.prototype.getInfo = function() {
    alert(this.name + "," + this.age);
};

var stu1 = new Student();
var stu2 = new Student();
stu1.name = 'Tony';
stu1.getInfo();
stu2.getInfo();

五)原型构造函数混合方式

function Student() {
    this.name = new Array();
    this.age = 23;
}

Student.prototype.getInfo = function() {
    alert(this.name + "," + this.age);
};

var stu1 = new Student();
var stu2 = new Student();
stu1.name.push("Chris");
stu2.name.push("Tony");
stu1.getInfo();
stu2.getInfo();

六)动态原型方式:在构造函数中,通过标质量让所有对象共享一个方法,而每个对象拥有自己的属性

function Student() {
    this.name = "Chris";
    this.age = 23;

    if (typeof Student.flag == "undefined") {
        Student.prototype.getInfo = function() {
            alert(this.name + "," + this.age);
        };
    }
    Student.flag = true;
}

var stu1 = new Student();
var stu2 = new Student();
stu1.getInfo();
stu2.getInfo();


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:9040次
    • 积分:135
    • 等级:
    • 排名:千里之外
    • 原创:3篇
    • 转载:20篇
    • 译文:0篇
    • 评论:0条
    文章存档