簡體   English   中英

調用Object Method會出現“Uncaught TypeError:is not a function”錯誤

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

未捕獲的TypeError:this.getIntStyle不是函數

我嘗試過使用:

    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 = 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() ,所以在X1this將引用uzak對象而不是沒有getIntStyle屬性的Div實例。

一種解決方案是使用類似的閉包變量

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

演示: 小提琴

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM