I have problem with JavaScript conversion. Here is an example:
var obj = {
x: 0,
y: 1,
z: 2
}
var b1 = typeof (obj.x),
b2 = typeof (obj.y),
b3 = typeof (obj.z);
b1 is "boolean"
, b2 is "boolean"
, b3 is "number"
.
I need to set variable to 0 and I need JavaScript to interpret it as a number. I've tried with conversions such as b1 = Number("0") but it doesn't help.
Sorry for the question above. It's true, b1, b2 and b3 all return number. This is my actual problem.
var SomeClass = function () {}
SomeClass.prototype = {
element: {},
startAt: 0,
length: 2,
get: function (prop) {
if (typeof (prop) === "undefined" || !(typeof (prop) === "string")) {
return false;
}
if (!this[prop]) {
return false;
}
return this[prop];
}
}
var sc = new SomeClass();
alert(typeof (sc.get("startAt")) + "\n" + typeof (sc.get("length")) + "\n" + typeof (sc.get("element")));
I would like to set startAt as an number.
I would like to set startAt as an number.
SomeClass.prototype.startAt
is a number (0
).
Your get
function explicitly returns false
if the property is "falsey":
if(!this[prop]){return false;}
In JavaScript, 0
, ""
, false
, undefined
, and null
are all "falsey", and so the condition above will be true and cause get
to return false
.
If your goal is to return false
if the property doesn't exist, you can do that like this:
if (!(prop in this)) { return false; }
That will check if the property exists on the object itself or its prototype, which I suspect is what you want. But if you only want to check the object itself and ignore properties on the prototype, that would be:
if (!this.hasOwnProperty(prop)) { return false; }
Bringing that all together, if your goal is for get
to return false
for properties that the object doesn't have (either its own, or via its prototype), then:
get : function(prop){
if (typeof prop !== "string" || !(prop in this)) {
return false;
}
return this[prop];
}
I've done a few things there:
typeof
is an operator, not a function, so you don't use parens around its operand (normally)
Since "undefined"
is !== "string"
, there's no need to check for it specifically when checking that prop
is a string.
I used !(prop in this)
to see if the object (or its prototype) has the property.
I combined the two conditions that returned false
into a single if
statement using ||
.