码迷,mamicode.com
首页 > 其他好文 > 详细

ES5 - 面向对象编程

时间:2017-09-17 00:21:33      阅读:226      评论:0      收藏:0      [点我收藏+]

标签:this   工厂模式   创建对象   字母   name   his   创建   code   create   

1. 创建对象的几种方式

/**
 * 普通方式
 */

var obj = {};
obj.name = ‘XingyaZhao‘;
obj.age = 23;
obj.intro = function () {
    return "My name is " + this.name + ", and I‘m " + this.age + ".";
};

alert(obj.intro());
/**
 * 工厂模式
 */

function createObject(name,age) {
    var obj = {};
    obj.name = name;
    obj.age = age;
    obj.intro = function () {
        return "My name is " + this.name + ", and I‘m " + this.age + ".";
    };
    return obj;
}

var obj1 = createObject(‘XingyaZhao‘,23);
var obj2 = createObject(‘HailinWang‘,22);
alert(obj1.intro());
alert(obj2.intro());
/**
 * 构造函数方式
 */

function Person(name, age) {
    this.name = name;
    this.age = age;
    this.intro = function() {
        return "My name is " + this.name + ", and I‘m " + this.age + ".";
    };
}

var zhao = new Person(‘XingyaZhao‘,23);
var wang = new Person(‘HailinWang‘,22);
alert(zhao.intro());
alert(wang.intro());

构造函数方式与工厂模式的区别

1.构造函数没有new Object,但它后台会自动var obj = new Object
2.this就相当于obj
3.构造函数不需要返回对象引用,它是后台自动返回的


构造函数方式的规范

1.构造函数也是函数,但函数名第一个字母大写
2.必须通过 new 构造函数名() 来创建对象,new Person()

ES5 - 面向对象编程

标签:this   工厂模式   创建对象   字母   name   his   创建   code   create   

原文地址:http://www.cnblogs.com/xingyazhao/p/7533258.html

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