Reputation: 1024
Problem:
Calling (console.log(d.yakinlik.uzak.X1())
) this function
function Div(isim) {
this.loc = document.getElementById(isim);
this.getStyle = function (stili) {
return window.getComputedStyle(this.loc).getPropertyValue(stili);
};
this.getIntStyle = function (stili) {
return parseInt(this.getStyle(stili), 10);
};
this.yakinlik = {
uzak: {
X1: function () {
return this.getIntStyle('left');
}
}
};
}
gives
Uncaught TypeError: this.getIntStyle is not a function
I have tried using:
this.yakinlik = {
uzak: {
},
orta: {
},
yakin: {
},
cokyakin: {
}
};
this.yakinlik.uzak.X1 = function () { return this.getIntStyle('left'); };
but it failed too. But when I do not use a method here this.yakinlik.uzak.X1 = function () { return this.getIntStyle('left'); };
like this this.yakinlik.uzak.X1 = this.getIntStyle('left');
it works (actually it gives NaN, but it is normal because it hasn't recomputed, so I have to use a method there. ).
Here is the involved pieces of the code:
'use strict';
function Div(isim) {
this.loc = document.getElementById(isim);
this.getStyle = function (stili) {
return window.getComputedStyle(this.loc).getPropertyValue(stili);
};
this.getIntStyle = function (stili) {
return parseInt(this.getStyle(stili), 10);
};
this.yakinlik = {
uzak: {
},
orta: {
},
yakin: {
},
cokyakin: {
}
};
this.yakinlik.uzak.X1 = function () { return this.getIntStyle('left'); };
}
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
var d = new Div("d");
d.loc.style.left = getRandomInt(0, window.innerWidth - 50) + "px";
d.loc.style.top = getRandomInt(0, window.innerHeight - 50) + "px";
console.log(d.yakinlik.uzak.X1() + " " + d.getIntStyle('top'));
How can I fix this without having to use a property there?
Thanks.
Upvotes: 2
Views: 1994
Reputation: 388316
The problem is you are calling d.yakinlik.uzak.X1()
, so inside X1
, this
will refer to the uzak
object not the Div
instance which does not have the getIntStyle
property.
One solution is to use a closure variable like
function Div(isim) {
this.loc = document.getElementById(isim);
this.getStyle = function (stili) {
return window.getComputedStyle(this.loc).getPropertyValue(stili);
};
this.getIntStyle = function (stili) {
return parseInt(this.getStyle(stili), 10);
};
var div = this;
this.yakinlik = {
uzak: {
X1: function () {
return div.getIntStyle('left');
}
}
};
}
Demo: Fiddle
Upvotes: 4