【发布时间】:2022-12-01 22:58:14
【问题描述】:
Object.prototype does not return values from function when using this.value.
I am trying to make a script that does something like this:
function testThing(a, b){
this.a = a;
this.b = b;
}
testThing.prototype.ba = new testThing(this.b, this.a);
Testing it using:
var test = new testThing(1, 2);
console.log(testThing.ba);
While it creates a testThing() object, both the values are null. I need the this.a/this.b values. I believe this is because the prototype isn't a function, but I'm not sure how to go about getting the values without a function. Is this possible?
【问题讨论】:
-
thisin the arguments for the constructor is not what you think it is. Though possible, but odd, why are you adding an instance to the prototype? What exactly are you trying to achieve? -
I am trying to make a swizzling mechanic for something, and while I can make it using Object.prototype functions, I'd rather have it be example.ba; instead of example.ba();
-
After you instantiate the
testThing, (ie.var test = new testThing(1, 2);), you can access the propertiesaandbby referencing them like this:test.aortest.b. -
Yes, that would work, however I'm trying to make an Object, not an individual thing I want it to be able to work with multiple variables, lets say test1 and test2
var test1 = new testThing(1, 2)var test2 = new testThing(3, 4)test1.ba;test2.ba; -
I suppose you need a getter instead of this prototype stuff. Drop constructors and use classes instead, it's much easier to set getters with classes.
标签: javascript