gpt4 book ai didi

javascript - 字符串原型(prototype)在浏览器中有效,但在 Node 中无效

转载 作者:行者123 更新时间:2023-11-30 21:16:21 25 4
gpt4 key购买 nike

Node :8.1.0

我有以下原型(prototype):

String.prototype.toSlug = function () {
return (<string>this)
.trim()
.toLowerCase()
.replace(/\s+/g, '-')
.replace(/[^\w\-]+/g, '')
.replace(/\-\-+/g, '-')
.replace(/^-+/, '')
.replace(/-+$/, '')
}

我使用的时候是这样的:

// Mongoose Database Model:
let project = new ProjectModel
project.slug = title.toSlug()

它似乎无法正常工作。它所做的只是删除第一个空格并添加破折号,如下所示:

// Original: "Bed Time Stories"
// Outputs: "BedTime-Stories"
// Expected: "bed-time-stories"

如您所见,它甚至没有将字符串转换为小写。

然而,当我在 jsfiddle 测试它时,它会创建正确的输出字符串。这是什么原因造成的?

最佳答案

interface String {
toSlug(): string;
}

String.prototype.toSlug = function () {
return (<string>this)
.trim()
.toLowerCase()
.replace(/\s+/g, '-')
.replace(/[^\w\-]+/g, '')
.replace(/\-\-+/g, '-')
.replace(/^-+/, '')
.replace(/-+$/, '')
}

var str = "Bed Time Stories";

console.log(str.toSlug());

我发现了错误,接口(interface)提供了 TypeScript 的契约,允许新方法的可见性。 JavaScript 实现提供调用方法时将执行的代码。这是代码中缺少的

来源:Extending functionality in TypeScript

关于javascript - 字符串原型(prototype)在浏览器中有效,但在 Node 中无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45651379/

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