简体   繁体   中英

access fields in javascript functions

I am having trouble accessing fields(variables) in a function definition. My question is with this code:

<script>
  function test(){ var book= [];}
  var arrs = test();
  alert(arrs.book);
</script>

It gives me 'undefined', why? I would expect it to be an empty value. Is there any way I can access this book array variable in arrs ?

arrs is undefined because test() doesn't return anything. All the function does is locally declare a variable and then end, so the local variable just falls out of scope and nothing happens.

Based on the usage, it looks like you want your function to maybe return an object?:

function test() {
    return { book: [] };
}

Or maybe the function should itself construct an object and you meant to call it with new ?:

function test() {
    this.book = [];
}
var arrs = new test();

Like Carcigenicate said, you are missing the return statement inside test().

function test(){ 
    var book= [];
    // missing return...
    return book;
}
var arrs = test();
alert(arrs);

Try it now.

 // old way function Test1() { this.books = ['t1'] } var t1 = new Test1() alert(t1.books) //es6 class class T2 { constructor() { this.books = ['t2'] } } var t2 = new T2() alert(t2.books) // plain object var t3 = { books: ['t3'] } alert(t3.books) // static field function T4() {} T4.prototype.books = [] var t4a = new T4(), t4b = new T4() t4a.books.push('t4') alert(t4b.books) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM