用构造函数来创建对象:
Html实例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>构造函数</title> </head> <body> <script> var CreateObj = function () { this.domain = 'xmubshw.com'; this.get = function (value) { var site = '小茗Ub生活网: '; return site + value; }; return this; }; 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));//访问方法 CreateObj.email = '908265504@qq.com'; CreateObj.hello = function () { return '小茗Ub生活网'; }; console.log(CreateObj.email); console.log(CreateObj.hello()); </script> </body> </html>
运行实例 »
点击 "运行实例" 按钮查看在线实例
向构造函数的prototype中添加成员,实现数据在实例间共享:
Html实例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>原型对象</title> </head> <body> <script> // 构造函数 var CreateObj = function () { this.domain = 'xmubshw.com'; this.get = function (value) { var site = '小茗Ub生活网: '; return site + value; }; }; // 原型属性的值是一个对象,保存着被当前函数实例共享的成员 // prototype 原型属性 CreateObj.prototype.email = '908265504@qq.com'; CreateObj.prototype.hello = function () { return '小茗Ub生活网'; }; var obj =new CreateObj() console.log(obj.email); console.log(obj.hello()); </script> </body> </html>
运行实例 »
点击 "运行实例" 按钮查看在线实例