1 var Pet = function(name, legs){ 2 this.name = name; 3 this.legs = legs; 4 }; 5 Pet.prototype.getDetails = function(){ 6 return this.name + " has " + this.legs + " legs"; 7 }; 8 9 var Cat = function(name){ 10 Pet.call(this, name, 4);// Call the parent object's constructor 11 }; 12 Cat.prototype = new Pet(); 13 14 Cat.prototype.action = function(){ 15 return "Catch a bird"; 16 }; 17 18 // create an instance of Cat in petCat 19 var petCat = new Cat('Flex'); 20 21 var details = petCat.getDetails(); 22 console.log("details:", details); 23 var action = petCat.action(); 24 console.log("action: " , action) 25 console.log("petCat.name, petCat.legs: ", petCat.name, petCat.legs) 26 petCat.name = 'Sylvester'; 27 petCat.legs = 7; 28 console.log("petCat.name, petCat.legs:",petCat.name, petCat.legs) 29 details = petCat.getDetails(); 30 console.log("details::", details) 31 32 // 这种继承方法没有提供对外部继承的保护,在涉及多个程序的复杂项目中这个缺点也许会影响很大。 33 // 另一个选项无需使用prototype 或new,而是利用javascript的“函数继承”特性来吸收和增强对象实例。
1 var pet = function(name, legs){ 2 var that = { 3 name : name, 4 getDetails : function(){ 5 return that.name + " has " + legs + " legs"; 6 } 7 }; 8 return that; 9 }; 10 11 var cat = function(name){ 12 var that = pet(name, 4); 13 14 that.action = function(){ 15 return 'Cathch a bird!'; 16 }; 17 18 return that; 19 }; 20 21 22 var petCat2 = cat('Flexi'); 23 console.log(petCat2); 24 25 details = petCat2.getDetails(); 26 console.log("details:", details); 27 28 action = petCat2.action(); 29 console.log("action:", action); 30 31 petCat2.name = 'Nick'; 32 console.log("name:::",petCat2.name); 33 petCat2.legs = 7; 34 console.log("legs:",petCat2.legs) 35 details = petCat2.getDetails(); 36 console.log("details::", details)
1 var startTime = new Date().getTime(); 2 for(var i = 0; i < 1000; i++){ 3 pice(); 4 var time = new Date().getTime() - startTime; 5 console.log(time); 6 } 7 8 var fastSin = function(steps){ 9 var table = [], 10 ang = 0, 11 angStep = (Math.PI * 2) / steps; 12 do{ 13 table.push(Math.sin(ang)); 14 ang += angStep; 15 }while(ang < Math.PI * 2); 16 return table; 17 };