您好,欢迎访问一九零五行业门户网

JavaScript 原型继承_js面向对象

object.prototype
javascript是基于原型继承的,任何对象都有一个prototype属性。object.prototype是所有对象的根,并且不可改变。
复制代码 代码如下:
object.prototype=null;
alert(object.prototype);//[object object]
object与object.prototype
object继承于object.prototype,增加一个属性给object.prototype上,同时也会反应到object上。如:
复制代码 代码如下:
object.prototype.namestr=object prototype;
object.prototype.getname=function(){return this.namestr};
alert(object.getname());//object prototype
function.prototype与object.prototype
由于object.prototype是万物之根,所以function.prototype也同时会继承object.prototype的所有属性。如:
复制代码 代码如下:
object.prototype.namestr=object prototype;
object.prototype.getname=function(){return this.namestr};
alert(function.prototype.getname());//object prototype
object/function/string/number/boolean/array与date
object/function/string/number/boolean/array与date都是函数,函数又继承于function.prototype, 所以更改function.prototype一样会影响到object/function/string/number/boolean/array与date。如:
复制代码 代码如下:
function.prototype.inittype='function type';
function.prototype.gettype=function(){return this.inittype};
//alert(object.gettype());//function type
//alert(date.gettype());//function type
//alert(number.gettype());//function type
//alert(string.gettype());//function type
//alert(boolean.gettype());//function type
alert(array.gettype());//function type
同样function.prototype也会把所受object.prototype的影响,传递给它的下一层级。如:
复制代码 代码如下:
object.prototype.namestr=object prototype;
object.prototype.getname=function(){return this.namestr};
alert(function.prototype.getname());//object prototype
alert(array.getname());//object prototype
复制代码 代码如下:
alert(boolean.prototype.getname());//object prototype
array/array.prototype与function.prototype/object.prototype
array是函数对象,受function.prototype的影响,而array.prototype不是函数对象,所不受function.prototype的影响,但所有对象受object.prototype的影响,所以array.prototype也会受object.prototype的影响。如:
复制代码 代码如下:
object.prototype.namestr=object prototype;
object.prototype.getname=function(){return this.namestr};
//alert(function.prototype.getname());//object prototype
//alert(boolean.prototype.getname());//object prototype
function.prototype.initfun=function(){
return 'function.prototype.initfun';
}
alert(array.initfun());//function.prototype.initfun
var arr=['a','b'];
alert(arr.getname());//object prototype
alert(arr.initfun());//error: arr.initfun is not a function
alert(arr.initfun);//undefined
其它类似信息

推荐信息