gpt4 book ai didi

javascript - 如何在 JavaScript 中向自定义类型添加方法

转载 作者:行者123 更新时间:2023-11-28 10:36:49 24 4
gpt4 key购买 nike

如果标题措辞不当,请道歉。

我本质上要做的是创建一个具有方法的自定义类型。它旨在充当泛型类型,因此它可以接受 stringint

const foo = new CustomType('value')

console.log(foo) // 'value'
console.log(foo + 'hello') // 'valuehello'
foo.method() // Do something

const bar = new CustomType([])

bar.push('foobar')

如果我使用类来存储值,我无法对其进行操作。

class CustomType {
constructor(value) {
this.value = value
}

method() {}
}

const foo = new CustomType('value')
console.log(foo + 'hello') // [object Object]hello"

类似于如何使用new Array()new String()

最佳答案

What you're trying to do is possible with prototypes (which is mimicked by classes in JS)

function CustomType(param) {
this.default = param;
}

CustomType.prototype.toString = function(postfix = "") {
return this.default + postfix;
};

CustomType.prototype.doSomething = function() {
console.log("I am doing something")
};


let customTypedObject = new CustomType("value");
console.log(customTypedObject.toString());// "value
console.log(customTypedObject.toString("hello")); // "valuehello


//Prototypal function inherited
customTypedObject.doSomething() //"I am doing something"

Coercion Overriding

What you're actually explaining sounds a lot like overriding coercion rules in javascript which defines how a custom type behaves with another primitive type. This is also possible.

function CustomType(param) {
this.default = param;
}
CustomType.prototype.valueOf = function() {
return this.default;
}

let customTypedObject = new CustomType("value")
console.log(customTypedObject + "hello"); //valuehello

了解更多 here

If you are trying to override the browser's default approach to "toString()" an object. This is not possible. However there is a way to do this inside nodejs though. Node internally calls "inspect" on an object which is available in node js's root object prototype. This can be overriden

//Works on NodeJS code (not in browser)
CustomType.prototype.inspect = function() {
return this.default;
};

let customTypedObject = new CustomType("value")
console.log(customTypedObject); // "value"

关于javascript - 如何在 JavaScript 中向自定义类型添加方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60358638/

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