JavaScript作用域和对象
JavaScript Scope and objects
将对象从一个函数传递到另一个函数是否需要任何特殊措施?我对面向对象的JavaScript比较陌生,所以如果有一个简单的修复方法,请原谅我。这里是我遇到的一个问题的一些示例代码。
function foo {
var x = 0;
var y = 0;
/* this is the JavaScript Object that is passed in
cell = {
left: {x: someInt, y: someInt},
up: {x: someInt, y: someInt},
right: {x: someInt, y: someInt},
down: {x: someInt, y: someInt},
x: someInt,
y: someInt
}
*/
this.turn = function(cell){
console.log(cell);
processNeighbors(cell);
smartMove(x,y, cell);
function smartMove(x,y,cell) {
// make a smart decision
}
function processNeighbors(x, y, cell) {
console.log(cell); // this is the line of the undefined error
// process all neighbors
}
}
我期望两个输出都是相同的,然而,processNeighbors
函数中的console.log()返回一个有效的响应,bar
函数返回一个'无法读取未定义的属性"值"。
那么当一个对象从一个函数传递到下一个函数时,它会超出作用域吗?我不会在任何函数中改变对象本身。
再看一遍你的代码:
function processNeighbors(x, y, cell) {
console.log(cell); // this is the line of the undefined error
// process all neighbors
}
processNeighbors
在函数作用域中创建了变量cell
。(第三个参数)
所以当你调用processNeighbors(cell);
的x
参数,如果你的函数将是单元格,y
和cell
参数将未定义。
从参数中删除cell
:
function processNeighbors(x, y) {
console.log(cell);
}
// or - if that was the intended way to call the function
function processNeighbors(cell) {
console.log(cell);
}
或者用正确的形参调用:
processNeighbors(x,y,cell);
我不评论你代码中的任何其他错误,因为我认为那些只是复制&粘贴错误。
作为一个非常简单的例子:
var x = 10;
function fn(x) {
alert(x);
}
function fn2() {
alert(x);
}
fn(5); // will alert 5
fn(); // will be undefined
fn(x); // will alert 10
fn2(); // will alert 10
相关文章:
- 向Angular作用域对象添加对象数组——TypeError
- 为什么对象的函数值没有自己的作用域
- 访问Javascript对象-Node.js的作用域问题
- 阻止控制器创建新的作用域对象
- 尝试将变量传递到对象中时的作用域问题'的方法构造函数
- 将对象作为参数传递时的 Javascript 函数作用域
- 在对象类上实现 jquery 作用域的最佳方法
- 嵌套的Angular指令触发父对象上的作用域函数
- 如何创建作用域的动态、基于实例的对象文字
- AngularJS select with ng选项不更新父作用域中的引用对象属性
- 作用域,在回调中丢失对对象的引用
- 在嵌套对象中继承此作用域
- Javascript作用域问题,对象在分配后没有数据
- Javascript-确定对象中是否有任何作用域引用
- 如何从不同的对象作用域访问可观察对象
- Javascript/jQuery对象作用域问题
- 2对象作用域相互冲突
- Javascript函数作用域vs对象作用域
- NodeJS不能访问子节点中的对象作用域
- 为什么将变量(在对象作用域之外)设置为等于对象方法返回未定义的结果?