Eva*_*ske 14 javascript oop types typeof instanceof
我正在尝试使用Javascript的一些更高级的OO功能,遵循Doug Crawford的"超级构造函数"模式.但是,我不知道如何使用Javascript的本机类型系统从我的对象中设置和获取类型.这就是我现在的方式:
function createBicycle(tires) {
var that = {};
that.tires = tires;
that.toString = function () {
return 'Bicycle with ' + tires + ' tires.';
}
}Run Code Online (Sandbox Code Playgroud)
如何设置或检索新对象的类型?type如果有正确的方法,我不想创建属性.
typeof或instanceof运营商对我的自定义对象?CMS*_*CMS 15
的instanceof操作者,在内部,后两个操作数的值是收集,使用抽象[[HasInstance]](V)操作,这依赖于原型链.
您发布的模式仅包括扩充对象,并且根本不使用原型链.
如果你真的想使用instanceof运算符,你可以将另一个Crockford的技术,Prototypal Inheritance与超级构造函数结合起来,基本上是从Bicycle.prototype它继承,即使它是一个空对象,也只是为了傻瓜instanceof:
// helper function
var createObject = function (o) {
function F() {}
F.prototype = o;
return new F();
};
function Bicycle(tires) {
var that = createObject(Bicycle.prototype); // inherit from Bicycle.prototype
that.tires = tires; // in this case an empty object
that.toString = function () {
return 'Bicycle with ' + that.tires + ' tires.';
};
return that;
}
var bicycle1 = Bicycle(2);
bicycle1 instanceof Bicycle; // true
Run Code Online (Sandbox Code Playgroud)
更深入的文章:
| 归档时间: |
|
| 查看次数: |
21382 次 |
| 最近记录: |