简体   繁体   中英

Confused about prototype in javascript

var y=function(){
    return new y.prototype.greeting();
}
y.prototype={
    greeting:function(){
        alert("hello world");
    }
}

new y();

the above code will alert("hello world");

but if I remove the .prototype and change that line to return new y.greeting();

an error will be occurred:

undefined is not a function

var y=function(){
    return new y.greeting();
}
y.prototype={
    greeting:function(){
        alert("hello world");
    }
}

new y();

why I can't call the greeting method without prototype here?

thanks a lot

y is a function, the [[Prototype]] of which is Function - so when you ask the interpreter to look up y.greeting for you, it first looks at y itself, then it checks Function.prototype and then it checks Object.prototype .

When you create a new y then the prototype property of y will be set on the object that is created. So if you did new (new y()).greetings() then you would get your alert .

Another way to think about it is the prototype property of a constructor function is the prototype of any child objects that will be created by calling new constructor . The actual internal [[Prototype]] of the constructor will always be based on whatever constructed it .

You can see this in the example I put together below. Object.getPrototypeOf will return the internal [[Prototype]] property, so we can see what is actually going on:

> var test = function() {}
> Object.getPrototypeOf(test)
function Empty() {}

// Setting the prototype property
// does not change the [[Prototype]] of test
> test.prototype = {x: 1}
> Object.getPrototypeOf(test)
function Empty() {}

// But it *does* change the prototype of
// objects *created by* test.
> var x = new test
> Object.getPrototypeOf(x)
Object {x: 1}

return new y.greeting(); tries to access an attribute (function) of y which doesn't really exist. That's why it throws the error 'undefined is not a function' because, the attribute of y contains a variable which contains a function. It's like three floors, where you cannot go to ground floor from the second floor without going to first floor; kind of hierarchy. Got it?

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