javascript 命名空间 继承 实现
javascript 命名空间的写法及实现方式: 
var collections;
if (!collections) collections = {};
collections.sets = {};
(function namespace() {
// ... Lots of code omitted...
// Now export our public API to the namespace object created above
collections.sets.AbstractSet = AbstractSet;
collections.sets.NotSet = NotSet; // And so on...
// No return statement is needed since exports were done above.
}());
if (!collections) collections = {};
collections.sets = {};
(function namespace() {
// ... Lots of code omitted...
// Now export our public API to the namespace object created above
collections.sets.AbstractSet = AbstractSet;
collections.sets.NotSet = NotSet; // And so on...
// No return statement is needed since exports were done above.
}());
javascript 继承实现方式:
混合方式
这种继承方式使用构造函数定义类,并非使用任何原型。对象冒充的主要问题是必须使用构造函数方式,这不是最好的选择。不过如果使用原型链,就无法使用带参数的构造函数了。开发者如何选择呢?答案很简单,两者都用。
在前一章,我们曾经讲解过创建类的最好方式是用构造函数定义属性,用原型定义方法。这种方式同样适用于继承机制,用对象冒充继承构造函数的属性,用原型链继承 prototype 对象的方法。用这两种方式重写前面的例子,代码如下:
function ClassA(sColor) {
this.color = sColor;
}
ClassA.prototype.sayColor = function () {
alert(this.color);
};
function ClassB(sColor, sName) {
ClassA.call(this, sColor);
this.name = sName;
}
ClassB.prototype = new ClassA();
ClassB.prototype.sayName = function () {
alert(this.name);
};
this.color = sColor;
}
ClassA.prototype.sayColor = function () {
alert(this.color);
};
function ClassB(sColor, sName) {
ClassA.call(this, sColor);
this.name = sName;
}
ClassB.prototype = new ClassA();
ClassB.prototype.sayName = function () {
alert(this.name);
};
                    
                
                
            
        
浙公网安备 33010602011771号