How can I structure an object to allow for initialization the same way as the stripe API:
var stripe = require("stripe")(
"sk_test_BQokikJOvBiI2HlWgH4olfQ2"
);
I have tried this
var example = (function () {
function example(api_token) {
this.token = api_token;
}
example.prototype.getSelf = function (callback) {
//do stuff
};
return example;
}());
module.exports = example;
but I get a Cannot set property 'token' of undefined
error when calling var sdk = require('./Example')(API_KEY);
Since your function isn't being called as a constructor (via the new
keyword), you need to make sure the function you provide doesn't expect to be called that way.
You could do this:
function Example(api_token) {
this.token = api_token;
}
// ...prototype, etc.
function example(api_token) {
return new Example(api_token);
}
module.exports = example;
Or don't use a constructor function at all, and use Object.create
:
var exampleProto = {
getSelf: function() {
// ...
}
};
function example(api_token) {
var o = Object.create(exampleProto);
o.token = api_token;
return o;
}
module.exports = example;
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.