JavaScript中Prototype的使用和实例
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> </body> </html> <script> (function(){ console.log("=========prototype的用法和误区========="); var A = function(){}; A.prototype.A1 = function(){ console.log("A1"); }; A.prototype.A2 = [1,2,3]; A.prototype.A3 = 1; var a1 = new A(); var a2 = new A(); a1.A2.push(4); a1.A3 = 2; console.log(a1.A3);//2 console.log(a2.A3);//1 console.log(a1.A2);//[1,2,3,4] console.log(a2.A2);//[1,2,3,4] /** 由于prototype是模版不是对象拷贝而是链接的方式 所以使用delete a1.A3, a1.A3并不会删除, 而是重新链上上一个值 **/ delete a1.A3; console.log(a1.A3);//1 console.log(a2.A3);//1 delete a1.A2; console.log(a1.A2); console.log("=========以下是继承部分========="); var B = function(){}; B.prototype = new A(); B.prototype.A3 = 10; var b1 = new B(); console.log(b1.A3);//[1,2,3,4] console.log("=========以下是constructor部分========="); var C = function(){}; C.prototype = { C1 : function(){} }; var c = new C(); console.log(a1.constructor ===A);//true /** C.prototype = { C1 : function(){} }; 等同于: C.prototype = new Object({ C1 : function(){} }); 所以: c.constructor===C 为 false **/ console.log(c.constructor===C);//false console.log(c.constructor===Object);//true console.log(C.prototype.constructor===Object);//true })(); </script>