Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/matlab/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript-继承和修改对象_Javascript_Inheritance_Var - Fatal编程技术网

Javascript-继承和修改对象

Javascript-继承和修改对象,javascript,inheritance,var,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

我正在尝试更改对象的属性,如下所示:

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的文档,他们在解释它方面比我在这里做得更好:

这是您函数的一个工作实现,唯一的区别是我使用了
文档。编写
,这样代码片段就会立即给出响应,应该是
12

secondFunction=function()
{
var bla={
答:1,,
};
bla.localFunction=function(){
//神奇之处在于:它当前绑定到此函数中的'bla'对象!
这个a=2;
}
返回bla;
}
firstFunction=函数(){
var测试=secondFunction();
文件编写(测试a);
testing.localFunction();
文件编写(测试a);
}

firstFunction()
您正在查找
关键字<代码>此
不是块范围!尝试使用
这个.a=2
。本质上,不,块中声明的变量与“local globals”不同,
this
关键字将包含其“scope”。这稍微简化了一点,但请阅读以下内容:我在这里没有看到任何继承。。。此外,IIRC,
a
不是
secondFunction
的变量,而是全局变量,即
console.log('a')
应该打印一些东西。@CedricReichenbach
a
在这里不是全局变量,
bla
是其父变量,bla由函数返回,因此分配给全局
测试
变量,因此,只有
测试
是直接全球性的
a
secondFunction
a
内部
bla的
返回值的变量。localFunction
是全局函数
a
inside
bla
不是。啊,我没有看到
a:1
inside
bla
。你的例子奏效了,但现在我想我知道它是如何按照我想要的方式工作的了。。。我应该简单地完成:console.log(a);显示2,不需要“这个”。现在我想弄明白为什么……因为当你设置一个变量而不使用
var
关键字时,它的作用域是自动全局的,但是你要避免设置全局的东西,因为它们会消耗不必要的内存。试着在对象和构造函数中使用
这个
,让它成为好朋友。尽可能避免全局变量,因为它们永远不会从内存中删除,因为它们已附加到宿主对象。我在上面向您展示的方法似乎是一种更安全的方法,可以存储多个实例,其中还包含一个键
a
。“这”令人困惑,但我只是真正明白了我必须做什么,lol.bla.a=2;将属性a更改为2,并且不会创建全局变量。无论如何,谢谢。
这不会让人困惑,也更安全。您将很快遇到引用对象的方式问题
bla.a=2
仅在这种特定情况下有效,如果您使用我缩短的、节省内存的代码,您将看到它不再有效,因为我不再启动变量,我直接返回它,因此
this
关键字现在具有明确的含义。啊,好吧,读一下Javascript,我们将在几年内讨论
这个
的优点:)