简体   繁体   中英

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. 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;

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.

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? Can anyone offer any suggestions to expose that prototype to the object method without having to redefine it?

EDIT I should have been more clear in my explanation. I updated my example above.

You forget about 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.
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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM