//构造函数可用来创建特定的对象
//创建一个对象
function Box(name,age)
{
//添加一个属性
this.name = name;
this.age = age;
//添加一个方法
this.run = function()
{
return this.name + this.age + "运行中...";
};
}
function Desk(name,age)
{
//添加一个属性
this.name = name;
this.age = age;
//添加一个方法
this.run = function()
{
return this.name + this.age + "运行中...";
};
}
//1.构造函数没有new Object,但它后台会自动 var obj = new Object
//2.this 相当于obj
//3.构造函数不需要返回对象的引用,它是后台自动返回的
//规范
//1.构造函数也是函数但函数名第一个字母大写
//2.必须new 构造函数名(), new Box(),而这个Box第一个字母也是大写
//3.必须使用new运算符
var box1 = new Box("Lee",100); //实例化
var box2 = new Box("Jack",200); //实例化
var box3 = new Desk("kkk",500); //实例化
//解决对象识别问题
//所有构造函数的对象都是object类型
alert(box1 instanceof Object);
//也是box对象
alert(box1 instanceof Box);
alert(box2 instanceof Box);
//可以识别了,因为box3是Desk对象的引用
alert(box3 instanceof Desk);
//对象冒充调用
function Box(name,age)
{
//添加一个属性
this.name = name;
this.age = age;
//添加一个方法
this.run = function()
{
return this.name + this.age + "运行中...";
};
}
var o = new Object();
//Uncaught TypeError: Object #<Object> has no method 'run'
//alert(o.run());
//如果想让o.run运行Box.run的方法
//让o冒充Box
//o把Box所有的功能都拿下来了
Box.call(o,"Lee",100);
alert(o.run());
function Box(name,age)
{
//添加一个属性
this.name = name;
this.age = age;
//添加一个方法
this.run = function()
{
return this.name + this.age + "运行中...";
};
}
var box1 = new Box("Lee",100); //实例化后地址为1
var box2 = new Box("Lee",100); //实例化后地址为2
//true 值相等
//alert(box1.name == box2.name);
<pre name="code" class="javascript">function Box(name,age)
{
//添加一个属性
this.name = name;
this.age = age;
//添加一个方法
//说明它是引用类型
this.run = run;
}
function run() //把构造函数的内部方法通过全局来实现,引用地址一致
{
//当普通函数调用run() this代表window
//当对象调用run()this代表该对象
return this.name + this.age + "运行中...";
}
var box1 = new Box("Lee",100); //实例化后地址为1
var box2 = new Box("Lee",500); //实例化后地址为2
alert(box1.run());
alert(box2.run());
//构造函数体内的方法的值是相等的//true//alert(box1.run() == box2.run());//打印方法的引用地址//因为他们比较的是引用地址//falsealert(box1.run == box2.run);
function Box(name,age)
{
//添加一个属性
this.name = name;
this.age = age;
//添加一个方法
//说明它是引用类型
this.run = new Function("return this.name + this.age + '运行中...'")
}
var box1 = new Box("Lee",100); //实例化后地址为1
var box2 = new Box("Lee",100); //实例化后地址为2
alert(box1.run());