日期:2014-05-16 浏览次数:20515 次
<script>
Array.prototype.max = function(){
alert("算法由你来写!");
};
var arr = new Array(1, 2, 3, 4, 5, 6);
var max = arr.max();
function oo () {
alert("oo");
}
oo.prototype.addMethodsOne = function() {
alert("addMethodsOne!!!");
}
new oo().addMethodsOne();
var a = function() {};
a.prototype.bbb = function() {
alert("var a = function(){}这样也可以!");
}
new a().bbb();
var b = {}; //这种写法是错误的哦!
b.prototype.ccc = function(){ //这种写法是错误的哦!
alert("cccc");
}
new b().ccc();//这种写法是错误的哦!
/*************************************************/
function test2() {
var bb = "1";
this.cc = "2";
this.d = function() {alert("dddd");};
}
test2.prototype.aaa = function () {
alert(this.bb); //undefined
alert(this.cc); //2
alert(this.d()); // ddd
}
new test2().aaa();
注意原型函数的变量用this来指定,那么在新的实例中就可以查找得到
/*********************************************/
//一般js包的编写也离不开这样的
var YPO = {
};
YPO.DOM = {
createElement:function() {
alert("createElement!");
},
getElement:function() {
alert("getElement!");
}
}
YPO.DOM.BUTTON = function() {
alert("creteButton");
}
YPO.DOM.createElement(); // createElement!
new YPO.DOM.createElement();// createElement!
YPO.DOM.BUTTON(); // creteButton
new YPO.DOM.BUTTON();// creteButton
</script>
<script>
//JavaScript对象都"继承"原型对象的属性。
//JavaScript中的所有函数都有prototype属性,它引用了一个对象
//虽然原型对象初始化时是空的,但是在其中定义的任何属性都会被该构造函数所创建的对象继承
var a = {
a1:12
}
a.cc = function() {
alert(this.a1);
}
a.cc();//
//a.prototype为空或不是对象,说明prototype是为函数提供的,不是为对象提供的。
//a.prototype.gg = function() {
// alert("gg");
//}
//说明对象(实例)可以动态添加属性
//方法
// 函数可以使用prototype
// 使得函数的对象(实例)继承原型的属性而已。
//alert(a1); undefined
//alert(this.a1);12-->
function dd () {
this.pp = 1;
function pa() {
alert("pa");
return "函数"
}
this.apa = pa;
}
dd.ddf = function() { //
alert(this.pp);
}
dd.prototype = {
ddm:function(){
var pp = "123";
alert(this.pp); // 继承构造函数中的属性
alert(this.apa()); // 继承构造函数中的函数
alert(this.aa); // 继承实例动态添加的属性
}
}
var ddd = new dd();
ddd.aa= 23;
//动态的添加属性,添加到了原型中去了。因为下面调用的时候输出来了this.aa的值
ddd.ddm();
alert("*************************************************");
function oo(){
this.vv = 123;
function pp() {
alert("***pp*************");
}
}
var p = new oo()
alert(new oo().vv); // 123
//alert(new oo().pp()); // 不支持此属性和方法
//alert (oo.pp()); // 不支持此属性和方法
oo.pp = function() {
alert("pppppp");
}
alert(oo.pp());// pppp
//dd.ddf();
//undefined; dd.ddf() 没有继承 dd()的属性
//在ddd.ddm中调用ddf也得不到,说明不是为构造函数添加属性
//说明dd.ddf()与dd()是两个毫不相干的函数而已,没有关系
//若要添加属性 可以直接来对象var a = {};a.cc={CXXXXX};
//ddd.ddf();//对象不支持这个方法
// alert(pp);undefined
// alert(this.pp); 1
</script>