Вы могли бы сделать что-то вроде:
var foo = {
a: 5,
b: 6,
init: function() {
this.c = this.a + this.b;
return this;
}
}.init();
Это была бы какая-то однократная инициализация объекта.
Обратите внимание, что вы фактически назначаете возвращаемое значение init()
до foo
, поэтому вы должны return this
.
Вместо ожидания произвольного тайм-аута установите script.onload
на функцию обратного вызова и выполните настройки там.
$button.addEventListener('click', () => {
$button.innerHTML = 'Waiting for response...';
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "https://checkout.stripe.com/checkout.js";
script.onload = function () {
// Now that we have the script loaded, we can create the stripe handler...
const handler = StripeCheckout.configure({
key: STRIPE_PUBLISHABLE_KEY,
image: 'https://stripe.com/img/documentation/checkout/marketplace.png',
locale: 'auto',
closed: function () {
resetButtonText();
},
token: function(token) {
fetch(`${LAMBDA_ENDPOINT}purchase`, {
method: 'POST',
body: JSON.stringify({
token,
amount,
idempotency_key: uuid()
}),
headers: new Headers({
'Content-Type': 'application/json'
})
})
.then(res => res.json())
.catch(error => console.error(error))
.then(response => {
resetButtonText();
let message = typeof response === 'object' && response.status === 'succeeded'
? 'Charge was successful!'
: 'Charge failed.'
$messageBox.querySelector('h2').innerHTML = message;
console.log(response);
});
}
});
// and use the handler to do whatever we want.
handler.open({
amount,
name: 'Test Shop',
description: 'A Fantastic New Widget'
});
};
document.getElementsByTagName("head")[0].appendChild(script);
});