gpt4 book ai didi

javascript - 我可以设置 Javascript 对象的类型吗?

转载 作者:可可西里 更新时间:2023-11-01 01:40:02 25 4
gpt4 key购买 nike

我正在尝试使用 Javascript 的一些更高级的 OO 功能,遵循 Doug Crawford 的“ super 构造函数”模式。但是,我不知道如何使用 Javascript 的 native 类型系统设置和获取对象的类型。这是我现在的方式:

function createBicycle(tires) {
var that = {};
that.tires = tires;
that.toString = function () {
return 'Bicycle with ' + tires + ' tires.';
}
}

如何设置或检索新对象的类型?如果有正确的方法,我不想创建 type 属性。

有没有办法为我的自定义对象覆盖 typeofinstanceof 运算符?

最佳答案

instanceof运算符,在内部,在收集两个操作数值之后,使用抽象 [[HasInstance]](V)操作,依赖于原型(prototype)链。

您发布的模式仅包含扩充对象,根本未使用原型(prototype)链。

如果你真的想使用instanceof操作符,你可以结合另一个Crockford的技术,Prototypal Inheritance使用 super 构造函数,基本上是继承自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

更深入的文章:

关于javascript - 我可以设置 Javascript 对象的类型吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1919295/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com