You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何调用对象内部的函数?调用时提示this.costPrice不是函数如何解决

报错原因

错误核心是JavaScript普通函数的this指向规则导致的:

  • 定义在sellingPrice内部的普通函数calculateProfit被直接调用时,它的this默认指向全局对象(浏览器环境为window,Node.js环境为global),而非外层的shop对象
  • 全局对象上没有定义costPrice方法,所以抛出this.costPrice is not a function的错误

修复方案

下面是三种最常用的修复方式:

方案1:闭包缓存外层this

在sellingPrice作用域内提前把指向shop对象的this存储到变量中,内部函数直接调用该变量即可:

var shop = {
    costPrice: function() {
        return 100;
    },
    sellingPrice: function() {
        // 缓存外层this,变量名可自定义为that/self/_this等
        var that = this;
        var calculateProfit = function() {
            // 直接用缓存的this调用对象方法
            return that.costPrice() * 0.2;
        }

        return this.costPrice() + calculateProfit();
    }
};

console.log(shop.sellingPrice()); // 输出120

方案2:将内部函数改为箭头函数

箭头函数没有独立的this,会自动继承外层作用域的this指向,是目前最简洁的修复方案:

var shop = {
    costPrice: function() {
        return 100;
    },
    sellingPrice: function() {
        // 改为箭头函数,this继承自外层sellingPrice的this(即shop对象)
        var calculateProfit = () => {
            return this.costPrice() * 0.2;
        }

        return this.costPrice() + calculateProfit();
    }
};

console.log(shop.sellingPrice()); // 输出120

方案3:调用时手动绑定this指向

通过call/apply/bind方法手动指定calculateProfit运行时的this指向:

var shop = {
    costPrice: function() {
        return 100;
    },
    sellingPrice: function() {
        var calculateProfit = function() {
            return this.costPrice() * 0.2;
        }
        // 调用时通过call把内部this绑定为当前shop对象
        return this.costPrice() + calculateProfit.call(this);
    }
};

console.log(shop.sellingPrice()); // 输出120

内容的提问来源于stack exchange,提问作者ThatRandomDeveloper

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.08 06:09:02