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

能否调用person对象walk方法内嵌套对象的right()与left()函数?

能否调用person.walk内部anotherPerson的right()和left()方法?

默认情况下不能直接调用,因为anotherPerson是walk函数内部的局部变量,它的作用域只限于walk函数内部,外部代码根本访问不到这个对象。

不过可以通过几种方式间接调用这些方法:

  • 在walk函数内部直接调用
    如果只是想在执行walk的时候触发这两个方法,直接在walk里调用就行:

    const person = {
      name: "JONY SINS",
      age: 25,
      walk() {
        let anotherPerson = {
          right() {
            console.log("right");
          },
          left() {
            console.log("left");
          },
        };
        anotherPerson.right(); // 直接调用right方法
        anotherPerson.left(); // 直接调用left方法
        console.log(this);
      },
    };
    person.walk(); // 执行后会输出"right"、"left"和person对象
    
  • 让walk返回anotherPerson对象
    修改walk方法,把内部的anotherPerson返回出去,这样外部就能拿到这个对象并调用它的方法:

    const person = {
      name: "JONY SINS",
      age: 25,
      walk() {
        let anotherPerson = {
          right() {
            console.log("right");
          },
          left() {
            console.log("left");
          },
        };
        console.log(this);
        return anotherPerson; // 返回内部对象
      },
    };
    // 调用方式
    const innerPerson = person.walk();
    innerPerson.right(); // 输出"right"
    innerPerson.left(); // 输出"left"
    
  • 通过闭包把方法暴露到外部
    比如在walk里把anotherPerson的方法挂载到person对象上,这样执行walk后就能直接通过person调用:

    const person = {
      name: "JONY SINS",
      age: 25,
      walk() {
        let anotherPerson = {
          right() {
            console.log("right");
          },
          left() {
            console.log("left");
          },
        };
        // 把内部方法挂载到person上
        this.right = anotherPerson.right;
        this.left = anotherPerson.left;
        console.log(this);
      },
    };
    person.walk();
    person.right(); // 输出"right"
    person.left(); // 输出"left"
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 02:45:40