问题
Class Example:
$(document).ready(function(){
var $ = function(id)
{
return document.getElementById(id);
}
class someClass
{
constructor()
{
...
}
someMethod()
{
...
}
}
... // rest of examples within this scope
});
So far I am able to create an instance of the class object when the window loads and then calling a method of that class on a button click event while also binding this
:
var obj = new someClass()
$('startButton').onclick = obj.someMethod.bind(obj)
All works fine and well until I want reset by deleting and creating a new instance of that class object. I have attempted a couple of different methods:
First, I attempted to call a function on button click that does one more task than before (instantiates a new object). I tried this both with declaring the variable obj
in the global scope specifying var
for the type and assigning it to null
, and then attempted to re-assign it and bind this
on button click. This works up until I attempt to call my setup()
method:
$('startButton').onclick = function() {
var obj = new someClass();
var obj.setup.bind(obj); // fails to call
}
I then attempted another route, which more or less landed me in the same spot:
$('startButton').addEventListener('click', function(event) {
var obj = new someClass();
console.log('obj is an instance of someClass?', obj instanceof someClass); // returns true
obj.setup.bind(obj); // fails to call
});
Without creating a new method within someClass
that manually resets all of my class attributes back to the initial values (I'd rather re-call the constructor), how can I gracefully instantiate a new class object on button click and be able to bind this
?
And when I do, is it okay to re-assign the variable holding the class object without first marking it for GC or deallocating it somehow? Nothing else references it. Apologies in advance if my terminology is off, I'm new to this.
回答1:
obj.setup.bind(obj)
binds a context to a function, but it does not call it. You either need to call it:
obj.setup.bind(obj)();
Or use .call()
instead of .bind()
:
obj.setup.call(obj);
However in this case, since you call the method directly on the instance, there is not really a need to bind anything:
$(document).ready(function() {
var $ = document.getElementById.bind(document); // <-- bind without calling
class someClass {
constructor() {
this.ready = false;
}
setup() {
this.ready = true;
}
}
$('startButton').addEventListener('click', function(event) {
var obj = new someClass();
obj.setup();
console.log(obj.ready); // true
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="startButton">Start</button>
来源:https://stackoverflow.com/questions/60691432/what-is-the-proper-way-of-creating-a-new-instance-of-a-class-onclick-in-javascri