javascript面向对象的几个结论(new,prototype)
二. javascript面向对象的几个结论(new,prototype)
================================================================================================================
---------------------------
2.1 引子
---------------------------
因为javascript最初设计的面向对象存在缺陷,导致如果每一个对象关于"类的方法都进行一次硬拷贝"的问题:
function ShowText(text){this.word = text;this.sing = function singFunction() {alert("HelloWorld!~");};}obj1 = new ShowText("sb1");obj2 = new ShowText("sb2");function ShowText(){this.sing = singFunction;}function singFunction(){ alert("HelloWorld!~"); }new ShowText().sing();function ShowText(){}ShowText.prototype.sing = function(){ alert( "HelloWorld!~");}new ShowText().sing();function ShowText(text){this.word = text;}var obj = new ShowText("hi,tomsui!~");alert(obj.word); // "hi,tomsui!~"var obj2 = new Object();obj2.constuct = ShowText;obj2.constuct("hi,tomsui!~");alert(obj2.word); // "hi,tomsui!~"var ball0=new Ball("creating new Ball");<==>var ball0=new Object();ball0.construct=Ball;ball0.construct("creating new ball"); function showText(text) { alert(test);}// 下面证明了showText的prototype属性是对象alert(typeof(showText.prototype)); // object// 下面说明了showText.prototype这个对象不能用默认toString()打印alert(showText.prototype); // [object, Object]// 下面证明showText.prototype.constructor的存在性alert(showText.prototype.constructor); // function showText(text) { alert(test); }alert(typeof showText.prototype.constructor); // function// 添加属性text属性function showText() {};showText.prototype.text = "HelloWorld!~"; // 添加shout()方法function showText() {}showText.prototype.shout = function(){alert("tomsui wants to smoke!~");};function ShowText() {};// 添加text属性ShowText.prototype.text = "HelloWorld!~";alert(new ShowText().text); // HelloWorld!~ // 添加shout()方法ShowText.prototype.shout = function(){alert("tomsui wants to smoke!~");};new ShowText().shout(); // tomsui wants to smoke!~function ShowText(){this.text = "tomsui is handsome!~";this.say = function(){alert("absolutely!")};} ShowText.prototype.text = "J.J. is handsome!~";ShowText.prototype.say = function(){alert("perhaps?")}; var obj = new ShowText();alert(obj.text); // tomsui is handsome!~obj.say(); // absolutely!function Person(name){this.name = name;this.wordsInHeart = "tell Rora I love her~";}var tts = new Person("tomsui"); // tell Rora I love her~alert(tts.wordsInHeart); Person.prototype.saySomeOtherWords = function(){alert("tell Rora I need her~")};tts.saySomeOtherWords();