对象的创建

var box = new Object();
box.name = "dang";
box.age = 100;
box.run = function(){
    return this.name+this.age+'运行中。。';
}
alert(box.run());

//上边的创建对象如果再要创建类似的对象需要大量的代码,例如在创建一个box2时
//创建一个集中实例化的方法,工厂模式

function createObject(name,age){
    var obj = new Object();
    obj.name=name;
    obj.age=age;
    obj.run=function(){
        return this.name+this.age+"运行中";
    };
    return obj;  //一定要返回对象
};
function createObject2(name,age){
    var obj = new Object();
    obj.name=name;
    obj.age=age;
    obj.run=function(){
        return this.name+this.age+"运行中";
    };
    return obj;  //一定要返回对象
};

var box1 = createObject("lee",100);
var box2 = createObject("jack",200);
var box3 = createObject2("lll",111);   //都是Object,就是识别问题,因为根本无法搞清楚他们到底是哪个对象的实例。

alert(box1.run());
alert(box2.run());
//构造函数创建,解决上边的识别问题,可以搞清他们到底是哪个对象的实例
function Box(name,age){   //不药用name
    this.name = name;
    this.age = age;
    this.run = function(){
        return this.name+this.age+"yinxingzhong";
    };  //分号要加
}
function Box2(name,age){
    this.name = name;
    this.age = age;
    this.run = function(){
        return this.name+this.age+"yinxingzhong";
    };  //分号要加
}

//1. 构造函数没有new Object,但后台会自动var obj = new Objeck();
//2. this就相当于obj
//3. 没有return语句

//1. 构造函数也是函数,并首字母大写
//2. 必须new构造函数来实例化

var box1 = new Box("lee",1000);
var box2 = new Box("jack",200);
var box3 = new Box2("kk",300);

alert(box1.run());
alert(box2.run());
alert(box3.run());

alert(box1 instanceof Box);  //true

另:冒充调用

//对象冒充调用
var o = new Object();
Box.call(o,"lee",100);
alert(o.run());
原文地址:https://www.cnblogs.com/by-dxm/p/6130366.html