JavaScript 范围和对象

标签 javascript scope

将对象从一个函数传递到另一个函数是否需要采取任何特殊措施?我对面向对象的 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 在函数作用域中创建 var cell。 (第三个参数)

因此,当您调用 processNeighbors(cell); 时,如果您的函数是 cell,则使用 x 参数,而 ycell 参数将是未定义的。

从参数中删除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

关于JavaScript 范围和对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31497614/

相关文章:

javascript - 使用类方法在 HTML5 Canvas 上绘图 : scope problems (JS, ES6)

javascript - GA 电子商务跟踪数据未发送

javascript - 按索引上下移动数组对象/元素

haskell - 在 Haskell 中,处理守卫时 where 子句的范围是什么?

c++ - 全局变量和范围 - C++

javascript - 高阶函数中 count++ 和 count+1 的区别

javascript - 如何使用 javascript 检查给定日期是否等于当前月份?

javascript - 将 Javascript 用户数组与 "Solution"数组匹配

javascript - 使用 AJAX 运行实时时钟

c++ - 使用Bandicam库