JavaScript作用域和对象

JavaScript Scope and objects

本文关键字:对象 作用域 JavaScript      更新时间:2023-09-26

将对象从一个函数传递到另一个函数是否需要任何特殊措施?我对面向对象的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参数,如果你的函数将是单元格,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