Javascript - 继承和修改对象

时间:2015-10-05 14:44:05

标签: javascript inheritance var

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

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&# 34;并将其修改为2.我错在哪里?

1 个答案:

答案 0 :(得分:0)

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

继承了您的函数的工作实现,唯一的区别是我使用了document.write,因此代码段立即吐出响应,应该是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(); 

这是一个更加清理的片段版本:

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