【问题标题】:Javascript - Inheriting and modifying an objectJavascript - 继承和修改对象
【发布时间】:2015-10-05 14:44:05
【问题描述】:

我正在尝试像这样更改对象的属性:

secondFunction = function()
{
    var bla = { 
    a:1, //properties
    };

    bla.localFunction = function(){
    a = 2; //can he read and modify this property?
    }

return bla; //return back object
}

firstFunction = function()
{
var testing = secondFunction(); //now testing is the object.
testing.localFunction(); //this is supposed to call localFunction and change the "a" property to 2
console.log(testing.a); //displays 1, not 2 as I thought it would
}

firstFunction(); 

我可能是错的(因为我是 javascript 新手),但是属性对于整个对象是全局的,并且由于 localFunction 是对象的一部分,我认为它应该能够读取属性“a”并对其进行修改到 2. 我哪里错了?

【问题讨论】:

  • 您正在寻找 this 关键字。 this 不是块作用域!尝试使用this.a = 2。本质上,不,块中声明的变量不像“局部全局变量”——this 关键字将包含它的“范围”。这有点简化,但请阅读:developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
  • 我在这里看不到任何继承...另外,IIRC,a 不会是secondFunction 的变量,而是一个全局变量,即console.log('a') 应该打印一些东西.
  • @CedricReichenbach a 在这里不是全局的,bla 是它的父级,bla 是函数返回的,因此分配给全局的testing var,因此只有testing 是直接的全球的。 areturnsecondFunction 的变量。
  • a inside bla.localFunction 是全局的。 a 里面 bla 不是。
  • 啊,我没看到bla里面的a:1

标签: javascript inheritance var


【解决方案1】:

让我给你一个指向 MDN 上 this 文档的链接,他们在解释方面做得比我在这里做得更好:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

这是你的函数的一个工作实现,唯一的区别是我使用了document.write,所以 sn-p 立即吐出响应,应该是12

secondFunction = function()
{
    var bla = { 
        a:1,
    };

    bla.localFunction = function(){
        // Heres the magic: this is currently bound to your `bla` object inside this function!
        this.a = 2;
    }

    return bla;
}

firstFunction = function(){
    var testing = secondFunction();
    document.write(testing.a);
    testing.localFunction();
    document.write(testing.a);
}

firstFunction(); 

这是一个更干净的 sn-p 版本:

function secondFunction(){
  // Dont waste precious memory to store something you could do in one go!
  return { 
    a: 1,
    // Functions are first-class in JS, so you can simply use them as values
    localFunction: function(){
      this.a = 2;
    }
  };
}

function firstFunction(){
  var testing = secondFunction();
  document.write(testing.a);
  testing.localFunction();
  document.write(testing.a);
}

firstFunction();

【讨论】:

  • 你的例子有效,但现在我想我知道它是如何按照我想要的方式工作的......我应该简单地完成:console.log(a);并且显示 2,不需要“这个”。现在我想弄清楚为什么......
  • 因为当你设置一个没有var关键字的变量时,它的作用域自动是全局的,但是你想避免设置全局的东西,因为它们会消耗不必要的内存。尝试在对象和构造函数中使用this,让它成为一个好朋友。尽可能避免全局变量,因为它们永远不会从内存中删除,因为它们附加到您的主机对象。我在上面向您展示的方式似乎是一种更安全的方式来存储多个实例,其中也包含一个键 a
  • "this" 令人困惑,但我真的弄清楚了我必须做什么,哈哈。 bla.a = 2;会将属性 a 更改为 2 而不会创建全局变量。无论如何谢谢你。
  • this 不会令人困惑,而且更安全。您将很快遇到引用对象的方式的问题。 bla.a = 2 仅在这种特定情况下有效,如果您使用我缩短的、内存高效的代码,您会发现它不再起作用,因为我不再启动变量,我直接返回它,因此this 关键字现在具有明确的含义。嗯,阅读 Javascript,我们将在几年内讨论 this 的优点 :)
猜你喜欢
  • 2019-01-30
  • 1970-01-01
  • 1970-01-01
  • 2012-01-31
  • 1970-01-01
  • 2013-02-22
  • 1970-01-01
  • 2014-11-26
  • 1970-01-01
相关资源
最近更新 更多