calling Object Method gives "Uncaught TypeError: is not a function" error

calling Object Method gives "Uncaught TypeError: is not a function" error

问题: 调用(console.log(d.yakinlik.uzak.X1()))这个函数

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');
            }
        }
    };
}

给出

Uncaught TypeError: this.getIntStyle is not a function

我试过使用:

    this.yakinlik = {
        uzak: {
        },
        orta: {
        },
        yakin: {
        },
        cokyakin: {
        }
    };
    this.yakinlik.uzak.X1 = function () { return this.getIntStyle('left'); };

但也失败了。但是当我不使用这里的方法时 this.yakinlik.uzak.X1 = function () { return this.getIntStyle('left'); }; 像这样 this.yakinlik.uzak.X1 = this.getIntStyle('left'); 它起作用了(实际上它给出了 NaN,但这是正常的,因为它没有重新计算,所以我必须使用那里的方法。) .

这里是涉及的代码片段:

'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'));

如何在不使用 属性 的情况下解决这个问题?

谢谢。

问题是您正在调用 d.yakinlik.uzak.X1(),因此在 X1 中,this 将引用 uzak 对象而不是 Div 实例没有 getIntStyle 属性.

一个解决方案是使用像

这样的闭包变量
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');
            }
        }
    };
}

演示:Fiddle