Reputation: 18811
How can I calculate pageSize.offset from the keyspageSizes.w/pageSize.h
inside the same object?
var pageSizes = {
w: parseInt(scope.page.imagewidth),
h: parseInt(scope.page.imageheight),
offset: (pageSize.w/pageSize.h)
}
console.log('page.offset', pageSizes.offset);
currently i'm getting a RefferenceError: pageSize is not defined.
I'm assuming this isn't possible. therefore, what would be the best way to do this?
Upvotes: 0
Views: 43
Reputation: 16726
apparently this works in firefox, opera, safari, chrome, and even IE9:
var pageSizes ={
w: parseInt(scope.page.imagewidth, 10), //Dont forget the radix!
h: parseInt(scope.page.imageheight, 10), //Dont forget the radix!
get offset () {
return this.w/this.h;
}
};
it's like the method one, but you don't have to call it, keeping it acting like the other properties.
console-friendly version:
var pageSizes ={
w: 5,
h: 10,
get offset () {
return this.w/this.h;
}
};
JSON.stringify(pageSizes); // == "{"w":5,"h":10,"offset":0.5}"
i'd always used Object.defineProperty (ODP) for getters and setters, but this seems to be a lot more supported than i thought. you learn something every day. it looks like a typo, what with the missing colon and "function" and all, but it works. very cool.
thank's to robG for his comment, which made me check the ref again.
see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get#Example:_Defining_a_getter_with_the_get_operator for details
Upvotes: 3
Reputation: 20445
Function has refence to special keyword "this" that points to Current Scope(or protypical scope of parent till global scope) or current Object Instance , Here Points to PageSizes Object Use this
var pageSizes = {
w: parseInt(scope.page.imagewidth),
h: parseInt(scope.page.imageheight),
offset: function() {
return this.w/this.h;
}
}
and then chnage this line , as offset it not an property it is a function now
console.log('page.offset', pageSizes.offset);
to
console.log('page.offset', pageSizes.offset());
Upvotes: 0
Reputation: 104785
Make it a function and use this
var pageSizes = {
w: parseInt(scope.page.imagewidth, 10), //Dont forget the radix!
h: parseInt(scope.page.imageheight, 10), //Dont forget the radix!
offset: function() {
return this.w/this.h;
}
}
console.log('page.offset', pageSizes.offset());
Also, dont forget your radix in the parseInt
function
Upvotes: 3