简体   繁体   中英

Why can't I set a JavaScript prototype inside a function?

Why can't I set the prototype inside of a function? For example why does this not work?

var Bar = function(){
   this.name='Bar'
}

var barProto = new Bar()  

var Foo = function(){
    this.prototype= barProto
}

var foo = new Foo()
console.log(foo.name) // undefined

But this does work:

var Bar = function(){
   this.name='Bar'
}

var barProto = new Bar()  

var Foo = function(){

}

Foo.prototype= barProto

var foo = new Foo()

console.log(foo.name) // Bar

I don't like the syntax of assigning the prototype after I have created the function.

this.prototype= barProto

is not equivalent to

Foo.prototype= barProto

this refers to a specific object which will be created by new Foo()

Foo is the constructor function. You set the prototype on the constructor, not on a specific instance.

More info on prototypical inheritance here: Mozilla docs

Because this.prototype is not the same as Foo.prototype . When Foo is called with new , any reference to this inside it will refer to the instance being created.

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