您当前的位置: 首页 > 学无止境 > JS经典实例 网站首页JS经典实例
javascript对象与原型-字面量方式创建构造函数与constructor
发布时间:2016-10-16 13:45:13编辑:雪饮阅读()
使用对象实例不能直接访问prototype,必须通过指针__proto__来访问:
function Box(){}
var box=new Box();
alert(box.__proto__);
可通过构造函数名(对象名)直接访问prototype:
function Box(){}
var box=new Box();
alert(Box.prototype);
使用构造函数字面量(键值对)方式创建原型对象:
function Box(){}
Box.prototype={
name:'雪饮',
age:24,
run:function(){
return this.name+this.age+'运行中';
}
};
var box=new Box();
alert(box.run());
用字面量的方式创建原型对象打印constructor时则为object,而普通的构造函数创建时则不是:
function Box(){}
Box.prototype={
name:'雪饮',
age:24,
run:function(){
return this.name+this.age+'运行中';
}
};
var box=new Box();
alert(box.constructor);
alert(Object);
因为Box.prototype={}这种写法其实就是创建了一个新对象
此时box.constructor==Object=='function Object(){[native code]}'
而普通的构造函数如:
function Box(){}
var box=new Box();
alert(box.constructor);
alert(Object);
此时:
box.constructor=='function Box(){}'
Object='function Object(){[native code]}';
也就是普通构造函数下,box.constructor与Object的值是不相同的
普通构造函数下constructor指回了Box,而字面量构造函数下则是指向了另外一个对象。
字面量方式构造函数constructor强制指回原对象:
function Box(){}
Box.prototype={
constructor:Box,//强制指定回原对象
name:'雪饮',
age:24,
run:function(){
}
}
var box=new Box();
alert(box.constructor);
alert(Object);
此时又和普通构造函数一样box.constructor和Object不相等了。
数组排序(从小到大):
var box=[5,2,3,4,1];
alert(box.sort());
查看原型对象里的方法:
alert(Array.prototype.sort);
alert(String.prototype.substring);
原型对象的函数自定义扩展:
String.prototype.addstring=function (){
return this+'你使用了string原型对象内置函数的扩展自定义函数';
}
var xy='雪饮';
alert(xy.addstring());
关键字词:javascript,对象,原型