继承和修改对象

Javascript - Inheriting and modifying an object

本文关键字:对象 修改 继承      更新时间:2023-09-26

我想改变一个对象的属性:

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。我哪里错了?

让我给你一个链接到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();