[英]Why can't I access my custom string prototype from an object method?
I have a custom string prototype that does some actions to a string;我有一个自定义字符串原型,可以对字符串执行一些操作;
String.prototype.norm_to_ascii=function(){return unescape(encodeURIComponent(this))};
In my example, the string that I want to apply the prototype to is a global object property that lives outside of the SampleObject object.在我的示例中,我想要应用原型的字符串是位于 SampleObject object 之外的全局 object 属性。 In my actual code it would be referenced like this;
在我的实际代码中,它会被这样引用;
var userObject = {
name: "SomeName",
id: "SomeID"
}
It works everywhere in my project (other js files) except for within a particular Object method;除了在特定的 Object 方法中之外,它在我的项目(其他 js 文件)中的任何地方都有效;
var SampleObject = { //This is in it's own js file called sampleobject.js
test: 0,
doStringThings {
let something = userObject.id.norm_to_ascii() //RETURNS userObject.id.norm_to_ascii is not a function
}
}
So in the SampleObject, I need to use the id, for example, but I need to do some basic decoding of the id value that is in the userObject which is what the string prototype does.例如,在 SampleObject 中,我需要使用 id,但我需要对 userObject 中的 id 值进行一些基本解码,这正是字符串原型所做的。
I can use this string prototype elsewhere.我可以在其他地方使用这个字符串原型。 This is in a chrome extension so I have defined the prototype in the service worker and it can be used in the popup and content pages as well as the service worker so it must have to do with the object method but I can't figure out why?
这是在 chrome 扩展中,所以我在服务工作者中定义了原型,它可以在弹出和内容页面以及服务工作者中使用,所以它必须与 object 方法有关,但我不知道为什么? Can anyone offer any suggestions to expose that prototype to the object method without having to redefine it?
谁能提供任何建议以将该原型公开给 object 方法而无需重新定义它?
EDIT I should have been more clear in my explanation.编辑我的解释应该更清楚。 I updated my example above.
我更新了上面的示例。
You forget about this
你忘了
this
this.otherTestValue.norm_to_ascii()
After seeing the updated question my conclusion is that you are defining the norm_to_ascii
function after you run it.在看到更新后的问题后,我的结论是您在运行它之后定义
norm_to_ascii
function。
Changing the order of the imports should fix the problem.更改导入的顺序应该可以解决问题。 Can you show us the structure of the project and where are you importing the file with that prototype?
您能否向我们展示项目的结构以及您在哪里导入带有该原型的文件?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.