Search code examples
javascriptnested-function

Javascript Call To Nested Function


I am relatively new to javascript, but have learned alot about OO programming from using Java. Either javascript is not very OO or I am missing something. Java has classes with methods much like javascripts functions, but I noticed that javascript functions also act as class objects not just methods. I am confused if a function can become an object shouldn't that object be able to have usable functions?

Javascript implementation:

function Div() {

var div = document.createElement('div');

 function setSize(width,height){

    div.position = 'absolute';

    div.style.width = width + 'px';
    div.style.height = height + 'px';
    div.style.background = 'black';

    document.body.appendChild(div);


}

}

HTML Script

<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
    <script type="text/javascript" src="jWebKit.js"></script>

    <script>

        var div1 = new Div();
        div1.setSize(100,100); //Does Not Work Irritating all whom love Java...

    </script>
</body>
</html>

Solution

  • Your setSize method is not defined as a member of the class here but as a function where the scope is limited to that function.

    There are many ways and documentation out there to explain how it works, but here you could have declared your function this way:

    function Div() {// Acts as a class?
    
        this.div = document.createElement('div');
        this.setSize = function(width,height){
            this.div.style.width = width + 'px';
            this.div.style.width = height + 'px';
        }
    }