/** * interface to implement Observer Pattern */ function iSubject(__constructor, proto) { this.constructor = __constructor; // 修正 constructor 属性 if (proto instanceof Object) { for (var p in proto) { if (proto.hasOwnProperty(p)) { this[p] = proto[p]; } } } } iSubject.prototype = { // 没有放在 iSubject 实例中是为了防止每个实现该接口的类都定义一遍方法 addObserver: function(observer) { if (!(observer instanceof iObserver)) { throw 'Invalid data type: "iObserver" type needed!'; } if (!(this.observers instanceof Array)) { this.observers = []; } if (typeof this.observers.indexOf == 'function') { if (this.observers.indexOf(observer) != -1) { return; } } else { var i = this.observers.length; while (i--) { if (this.observers[i] === observer) { return; } } } this.observers.push(observer); }, removeObserver: function(observer) { var index; if (!(this.observers instanceof Array)) { return; } if (typeof this.observers.indexOf == 'function') { index = this.observers.indexOf(observer); } else { var i = this.observers.length; while (i--) { if (this.observers[i] === observer) { index = i; } } } if (typeof index != 'undefined' && index != -1) { return this.observers.splice(index, 1)[0]; } }, notify: function(event) { if (!(this.observers instanceof Array)) { return; } var i = 0, len = this.observers.length; for (; i < len; i++) { this.observers[i].handle(this, event); } } } function iObserver(__constructor, proto) { iSubject.call(this, __constructor, proto); // this.constructor = __constructor; // // if (proto instanceof Object) { // for (var p in proto) { // if (proto.hasOwnProperty(p)) { // this[p] = proto[p]; // } // } // } } iObserver.prototype.handle = function(subject, event) {} // 使用 function M(){} M.prototype = new iSubject(M, { start: function() { // ... this.notify('start'); } }); function V(){} V.prototype = new iObserver(V, { handle: function(m, event) { // ... } }); var m = new M, v = new V; m.addObverser(v); m.start(); /** * JavaScript 的 instanceof 运算符 和 isPrototypeOf() 方法 */ function A(){ // ... } var a = new A; a instanceof A // true a instanceof Object // true A.prototype.isPrototypeOf(a) // true Object.prototype.isPrototypeOf(a) // true // 说明: // obj instanceof ConstructorFunc // 检测 obj 的内部属性(一般是 __proto__ )链中是否包含 ConstructorFunc.prototype // 这个表达式是和 // ConstructorFunc.prototype.isPrototype(obj) 效果一样 // // // JavaScript 中每个对象都有个内部属性(__proto__), 它链到创建该对象的构造函数的原型 // // isPrototypeOf 方法是在 Object 原型中定义的, Object 原型中的方法有: // hasOwnProperty() // isPrototypeOf() // propertyIsEnumerable() // toLocaleString() // toString() // valueOf()