继承和修改对象
Javascript - Inheriting and modifying an object
我想改变一个对象的属性:
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();
相关文章:
- 从客户端获取修改后的对象,并将其与服务器上的原始对象组合
- 可以从Chrome扩展修改窗口对象吗
- 修改JSON对象
- 使用AngularJS修改对象位置只需一次
- 修改express.js中的res对象
- 如何避免在这种情况下修改事件对象
- 修改鼠标事件对象的“目标”以进行事件委派
- Angular 2神秘地修改具有相同值的对象中的所有子嵌套相似对象
- Reactjs:在修改对象之前,是否需要复制处于组件状态的对象
- 重复修改ng内Angular Scope内的对象
- 如何通过使用谷歌地图从文本字段提交来修改javascript对象中的数据
- Lodash搜索对象属性并修改值
- 修改角度阵列对象加载
- 使用扩展运算符和析构函数运算符修改不可变对象的最短方法是什么
- 从函数内部修改角度工厂对象
- AngularJS:深度对象修改后视图不更新
- 为什么对象原型中的属性不能被对象修改
- 循环中的json对象修改不起作用
- 从子对象修改原型上的字段
- 为什么ngResource会在收到响应后将保存的对象修改为:g {0: "O", 1: "