var function{prototype:prototype{constructor:constructor == function}}还不明白?看图吧:
prototype的作用:
这个prototype到底有什么作用呢?看下面的例子:
function jb51(){}jb51.prototype.name = "a";var test = new jb51();alert(test.name)//"a";奇怪吧,明明没有为test设置name属性,可是为什么会有值?var name = "js";function jb51(name){alert(this.name);//"css"}jb51.prototype.name = "css";var test = new jb51();test()为什么alert的值不是“js”?这个过程大致如下:var test={};uw3c.call(test);第一步是建立一个新对象(test)。function person(name){this.sayHi = function(){alert("hi " + this.name);}this.name = name;}var p = new person("dan");p.sayHi(); 以上,使用new关键字,通过对象(函数也是特殊对象)创建一个对象实例。function animal(){}var cat = new animal();cat.color = "green"; 以上,color这个字段只属于当前的cat实例。--使用Prototypefunction animal(){}animal.prototype.color= "green";var cat = new animal();var dog = new animal();console.log(cat.color);//greenconsole.log(dog.color);//green 通过Prototype不仅可以添加字段,还可以添加方法。function animal(){}animal.prototype.color= "green";var cat = new animal();var dog = new animal();console.log(cat.color);//greenconsole.log(dog.color);//greenanimal.prototype.run = funciton(){console.log("run");}dog.run(); 原来通过prototype属性,在创建对象之后还可以改变对象的行为。Array.prototype.remove = function(elem){var index = this.indexof(elem);if(index >= 0){this.splice(index, 1);}}var arr = [1, 2, 3] ;arr.remove(2); 除了通过prototype为对象定义属性或方法,还可以通过对象的构造函数来定义类的属性或方法。function animal(){this.color = "green";this.run = function(){console.log("run");}}var mouse = new animal();mouse.run(); 以上做法的也可以让所有的animal实例共享所有的字段和方法。并且还有一个好处是可以在构造函数中使用类的局部变量。function animal(){var runAlready = false;this.color = "green";this.run = funciton(){if(!runAlreadh){console.log("start running");} else {console.log("already running")}}} 其实,一个更加实际的做法是把通过构造函数结合通过prototype定义一个类的字段和行为。function animal(){var runAlready = false;this.run = function(){if(!runAlready){console.log("i am running");} else {console.log("i am already running");}}}animal.prototype.color = "";animal.prototype.hide = funciton(){console.log("");}var horse = new animal();horse.run();horse.hide(); Prototype允许我们在创建对象之后来改变对象或类的行为,并且这些通过prototype属性添加的字段或方法所有对象实例是共享的。