[关闭]
@openxy 2016-04-24T19:47:27.000000Z 字数 1387 阅读 1650

JavaScript中的6种对象构建模式


参考:
- JavaScript高级程序设计(第2版)
- http://www.ruanyifeng.com/blog/2012/07/three_ways_to_define_a_javascript_class.html

  1. var Obj = new Object;
  2. Obj.name = 'sun';
  3. Obj.showName = function() {
  4. alert('this.name');
  5. }
  1. function createObj(name) {
  2. var tempObj = new Object;
  3. tempObj.name = name;
  4. tempObj.showName = function () {
  5. alert(this.name);
  6. };
  7. return tempObj;
  8. }
  9. var obj1 = createObj('obj_one');
  10. var obj2 = createObj('obj_two');
  1. function showName () {
  2. alert(this.name);
  3. }
  4. function createObj(name) {
  5. var tempObj = new Object;
  6. tempObj.name = name;
  7. tempObj.showName = showName;
  8. return tempObj;
  9. }
  10. var obj1 = createObj('obj_one');
  11. var obj2 = createObj('obj_two');
  1. function Obj(name) {
  2. this.name = name;
  3. this.showName = function () {
  4. alert(this.name);
  5. }
  6. }
  7. var obj1 = new Obj('obj_one');
  8. var obj2 = new Obj('obj_two');
  1. var Obj = function () {}
  2. Obj.prototype.name = 'me';
  3. Obj.prototype.flag = new Array('A', 'B');
  4. Obj.prototype.showName = function () {
  5. alert(this.name);
  6. }
  7. var obj1 = new Obj();
  8. var obj2 = new Obj();
  9. obj1.flag.push('C');
  10. alert(obj1.flag); // A,B,C
  11. alert(obj2.flag); //A,B,C
  1. var Obj = function (name) {
  2. this.name = name;
  3. this.flag = new Array('A', 'B');
  4. }
  5. Obj.prototype = {
  6. showName : function () {
  7. alert(this.name);
  8. }
  9. }
  10. var obj1 = new Obj();
  11. var obj2 = new Obj();
  12. obj1.flag.push('C');
  13. alert(obj1.flag); // A,B,C
  14. alert(obj2.flag); //A,B
  1. var Obj = function (name) {
  2. this.name = name;
  3. this.flag = new Array('A', 'B');
  4. if (typeof Obj._init == 'undefined') {
  5. Obj.prototype = {
  6. showName : function () {
  7. alert(this.name);
  8. }
  9. };
  10. Obj._init = true;
  11. }
  12. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注