简体   繁体   中英

JS OO basics and why doesn't this work?

Aparently I fail to understand how to use simple OO patterns in JS. Hopefully someone can just give me a hint where I am going wrong.

Here is a short test. When loaded into a browser the development console shows two things:

  1. undefined as value of Element.Display and

  2. an obviously failed assignment to Board.Display because of this

Interesting detail: the debug output of Element does contain Display ...

My question: why doesn't this work?


File "test.html":

<html lang="en">

    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <script type="text/javascript" src="test.js"></script>
    </head>

    <body>
        Hello world!
    </body>
</html>

File "test.js":

Element: {
    Display = function() {
        // declare something
        // do something
    } // Element.Display
}; // Element

var Board = function() {
    // debug output
    console.log(Element);
    console.log(Element.Display);
    // declare something
    Display: new Element.Display();
    // do domething
}();

The above example at jsfiddle.net: Example

Element: is a label .

You want to assign an object to a variable:

Element =

You should declare the variable first though.

var Element =


Then we have this.

Display = function() {
    // declare something
    // do something
} // Element.Display

Before you fix the last problem, it is valid (because it is a function assignment to a global inside a block).

After you fix that problem it becomes an error.

Use : between property names and property values inside an object literal.


The second half of your code has problems too.

var Board = function() {
    // Also a label
    Display: new Element.Display();

    // there is no return statement in this function
    // so you are assigning undefined to Board
}();

This could help clarify things a little:

Element is declared as an object with a function named 'Display'.

var Element = {
    Display : function() {
        console.log('display something');
    } 
}; 

Board is declared as a function that calls the Display function of the Element object.

var Board = function() {        
    return Element.Display();       
}();

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