While using Javascript for some fun, I ran into a morass of difficulties surrounding classes and objects. I thought I got that it is not Java, nor c++. Finally, I took my problems into a smallish example to study this.
Running the example produces output:
>>>>>> keys aprop,bprep,cprep,dprop,bprop,cprop.
I expected output:
>>>>>> keys aprop,bprep,cprep,dprop.
If duplication, why are not aprop and dprop also duplicated? I had thought that by using getOwnPropertyNames I prevented prototype keys. Is there a way to fix this short of comparing each key to eliminate duplicates?
<script>
var objList = [];
class TestObj {
constructor(aprop, bprop, cprop) {
this.aprop = aprop;
this.bprep = bprop;
this.cprep = cprop;
this.dprop = 0;
}
getAprop() { return aprop; }
getBprop() { return bprop; }
getCprop() { return cprop; }
getDprop() { return dprop; }
setAprop(arg) { aprop = arg; }
setBprop(arg) { bprop = arg; }
setCprop(arg) { cprop = arg; }
setDprop(arg) { dprop = arg; }
}
function create() {
putList();
var t1 = objList[1];
alert("fromlist "+t1);
var keys = Object.getOwnPropertyNames(t1);
console.log(">>>>>> keys "+keys);
}
function putList() {
onlist(1, "one" [1]);
onlist(2, "two", [2, 2]);
onlist(3, "three", [3, 3, 3]);
}
function onlist(a, b, c) {
var item = new TestObj();
item.aprop = a;
item.bprop = b;
item.cprop = c;
objList.push(item);
}
create();
</script>
function TestObj() { this.aprop = 0; } var keys = Object.getOwnPropertyNames(new TestObj()); console.log(keys);?Testobj.prototype.somekey?