码迷,mamicode.com
首页 > 编程语言 > 详细

JavaScript创建自定义对象

时间:2016-01-03 17:09:03      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:

// 1.工厂函数(factory function)
function createCat(catName) {
    var oCat = new Object();
    oCat.name = catName;
    oCat.color = "black";
    oCat.call = "Miao~";
    oCat.run = function() {
        alert(this.name + " is running!");
    };
    return oCat;
}

var oCat1 = createCat("Tom");
oCat1.run();

var oCat2 = createCat("Ken");
oCat2.run();

// 2.构造函数方法
function Dog(dogName, dogColor) {
    this.name = dogName;
    this.color = dogColor;
    this.call = function() {
        alert(this.name + " boof!");
    };
}

var dog1 = new Dog("Bob", "black");
alert("dog1.name " + dog1.name + " dog1.color " + dog1.color);
dog1.call();
var dog2 = new Dog("Poppy", "color");
alert("dog2.name " + dog2.name + " dog2.color " + dog2.color);
dog2.call();

// 3.构造函数+原型方法
function Person(personId, personName) {
    this.id = personId;
    this.name = personName;
    this.hobby = new Array();
}
Person.prototype.driver = function() {
    alert(this.name + " driver Car");
};

var person1 = new Person(1, "Joe");
person1.hobby.push("Reading");
person1.hobby.push("Shoot");
alert("person hobby:" + person1.hobby);
person1.driver();

var person2 = new Person(2, "Make");
person2.hobby.push("Paint");
person2.hobby.push("Sport", "Eating");
alert("person hobby:" + person2.hobby);
person2.driver();

 

JavaScript创建自定义对象

标签:

原文地址:http://www.cnblogs.com/learnhow/p/5096457.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!