对于javascript自己而言是基于对象的,任何元素均可以当作对象。然而类型和对象是不一样的,而咱们所讲的prototype属性便是基于类型的一种属性。对于prototype的基本使用就如对象的建立及属性赋值同样的简单。直接经过赋值操做便可完成属性的建立。 javascript
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>test</title> </head> <body> <script> /* * 关于prototype,理解这个颇有必要 * 能够在类型上使用proptotype来为类型添加行为。这些行为只能在类型的实例上体现。 * JS中容许的类型有Array, Boolean, Date, Enumerator, Error, Function, Number, Object, RegExp, String * 之后这样分,没有实例化的类称为类型,实例化的类称为对象实例简称实例 */ Object.prototype.name = "zhangsan"; Object.prototype.nihao = function(){ alert("i can method name is "+this.name); } var obj = new Object(); obj.nihao(); alert(obj.name); //在实例上不能使用prototype,不然会发生编译错误 obj.prototype.sex = "男";//error,没法给一个实例prototype var o = { name:"zhangsan" } o.prototype.age = 30;//error,没法给一个实例prototype //能够为类型定义“静态”的属性和方法,直接在类型上调用便可 alert(Object.name); Object.nihao(); //实例不能调用类型的静态属性或方法,不然发生对象未定义的错误。 Object.class = "三年二班";//类静态属性 var ob = new Object(); alert(ob.class); //error 实例不能调用类型的静态属性和方法 //能够在外部使用prototype为自定义的类型添加属性和方法。 function Mytest(){ this.name = "zhangsan"; this.age = 20; } Mytest.prototype.hello = function(){ alert(this.name); } var m = new Mytest(); m.hello(); //在外部不能经过prototype改变自定义类型的属性或方法。 //该例子能够看到:调用的属性和方法还是最初定义的结果。 Mytest.prototype.name = "lisi"; var mm = new Mytest(); alert(mm.name); //能够在对象实例上改变或增长属性。(这个是确定的) //也能够在对象上改变或增长方法。(和广泛的面向对象的概念不一样) mm.name2 = "lisi"; mm.hello = function(){ alert(this.name2); } //mm.hello(); //继承,这个例子说明了一个类型如何从另外一个类型继承。 function Mytest2(){} Mytest2.prototype = new Mytest; var m2 = new Mytest2(); alert(m2.name); //这个例子说明了子类如何重写父类的属性或方法。 Mytest2.prototype.name = "wangwu"; Mytest2.prototype.hello = function(){ alert('i can mytest2 extend Mytest save method hello'); } var m3 = new Mytest2(); m3.hello(); //子类中的name属性值不会被父类覆盖 function Mytest3(){ this.name = "子类中的name属性值不会被父类覆盖"; this.age = 20; } Mytest3.prototype = new Mytest(); var m4 = new Mytest3(); alert(m4.name); </script> </body> </html>