1. 写一个构造函数来创建对象
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>构造函数创建对象</title> </head> <body> <script> var CreateObj = function() { this.domain = 'baidu***'; this.get = function(value) { var site = '百度: '; return site + value; } }; var obj1 = new CreateObj(); console.log( obj1.domain ); console.log( obj1.get( obj1.domain) ); var obj2 = new CreateObj(); console.log( obj2.domain ); console.log( obj2.get(obj2.domain) ); </script> </body> </html>
结果如下图
2. 向构造函数的prototype中添加成员,实现数据在实例间共享
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>向构造函数的prototype中添加成员,实现数据在实例间共享</title> </head> <body> <script> var CreateObj = function() { this.domain = 'php.cn'; this.get = function(value) { var name = 'php中文网: '; } }; var obj1 = new CreateObj(); CreateObj.prototype.site = 'baidu***'; CreateObj.prototype.hello = function() { return '百度一下'; } console.log( obj1.site ); console.log( obj1.hello() ); </script> </body> </html>
如下图
。。。