代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>oop</title> <script charset="utf-8" type="text/javascript"> function Person() { } Person.prototype = { name : 'Lucy', age : 23, friends : ['Kinsey','Godwin','David'], sayHello: function () { document.write('hi,boy' + '<br><br>'); } }; var p = new Person(); var p2= new Person(); document.write(p.sayHello()); p.friends.push('Berkhoom'); document.write(p.friends + '<br><br>'); document.write(p2.friends + '<br><br>'); /** * 动态原型模式(代码封装到原型对象中) */ function ProgramLanguage(name, author) { this.name = name; this.author = author; //动态原型模式 if(typeof this.helloWorld != "function"){ this.helloWorld = function () { document.write('Welcome to ' + this.name + ', I\'m created by ' + this.author + '.' + '<br><br>'); } } } var language = new ProgramLanguage('Python','Guido van Rossum'); language.helloWorld(); /** * 稳妥构造模式: double object(稳妥对象) 非常安全的环境中 * 1. 没有构造函数 * 2. 不能使用this对象 */ function Country(name, area){ //创建一个需要返回的对象 var obj = new Object(); //这里可以定义一个私有的变量和函数private var name = name; obj.sayName = function() { document.write(name + '<br><br>'); } return obj; } var c = new Country('CHINA',960); c.sayName() </script> </head> <body> </body> </html>结果;
