Saturday, 15 April 2017

Why is it not possible to call functions directly from an object without function expression?

function Car(make, model) {
    this.make = make
    this.model = model

    console.log(" Iam inside the object" )
    this.whatsmymodel = function () {
        console.log(" Iam " , this.model)
    }

    function whatsmymake() {
        console.log(" Iam " , this.make)
    }
}

function whatsthis() {
    console.log (" This is a function")
}

Car.prototype.whoami = function () {
        console.log(" Iam " , this.make + " " + this.model)
}

var tesla = new Car("Tesla", "ModelS")
tesla.whoami()
tesla.whatsmymodel()
tesla.whatsmymake() // Error!!

whatsthis()

How come I get error for tesla.whatsmymake()

TypeError: tesla.whatsmymake is not a function

I understand it is possible in the new ES6 class but wouldnt it be easier to define a function within a function constructor ? It is letting me define but doesnt allow me to call - why is that ?



via Victor

No comments:

Post a Comment