简体   繁体   中英

Function and function group with same name in javascript object

I have following object in JavaScript . I am confused in how to access object.demo() and object.demo.inner() . The object.demo.inner() worked fine but object.demo is not working. I have the requirement that the name should be same. Why is the function not overloading here?

var object = {
    // object.demo()
    demo: function(str, pathStr) {
        console.log('function 1')
    },

    demo: {
         // object.demo.inner()
        inner: function () {
            console.log('inner')
        }
    }
}

object.demo.inner() //working
object.demo() //not working

Function is an object in javascript so it can have other properties. So you can assign inner function to a property of object.demo object:

var object = {
    // object.demo()
    demo: function(str, pathStr) {
        console.log('function 1')
    }
}

// object.demo.inner
object.demo.inner = function () {
    console.log('inner')
}

Actually there is no function object.demo , because you are overwriting the same object with another object. This behaviour is prohibited in ES5 with 'strict mode' , but not in ES6.

You could take the outer object and assign the function to the inner property later.

 var object = { demo: function(str, pathStr) { console.log('function 1') } }; object.demo.inner = function () { console.log('inner'); }; object.demo.inner(); object.demo(); 

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