简体   繁体   中英

Issue with object not inheriting its prototype's methods

Check out the image. How can this be? Aren't objects supposed to inherit its prototype's methods?

King <-- FixedMovementPiece <-- Piece

Piece has the setXY method.

奇怪的行为

__proto__ (defined in most current browsers but not in the current ECMAScript specification) is what gets used when the prototype chain is being searched through.

prototype is used when a function is called as a constructor, to assign the __proto__ property of the new object. As prototypes are typically not constructors, prototype.prototype is rarely useful or even defined.

examples:

Array.prototype === (new Array()).__proto__ //true
(new Array()).prototype === undefined //true

var a = {0:'a', 1:'b', 2:'c', length:3}
a.toString() // "[object Object]"
var a = {0:'a', 1:'b', 2:'c', length:3, __proto__:Array.prototype}
a.toString() // "a,b,c"

var obj = {__proto__:{}}
obj.name // undefined
obj.__proto__.name = "someString"
obj.name // "someString"
obj.name2 = "anotherString"
obj.__proto__.name2 // undefined

Objects inherit from their constructor's prototype (ie the one the constructor had when the the instance was created), which is referenced by an internal [[Prototype]] property.

Only functions have a prototype property by default. eg

// Declare function
function Foo(name) [
    this.name = name;
}

// Add a showName method to its prototype
Foo.prototype.showName = function() {
    return this.name;
}

// Create an instance
var foo = new Foo('foo');

// Call inherited method
foo.showName(); // foo

There is also a non standard __proto__ property in Mozilla browsers that references an object's [[Prototype]] , it may be in ES6 but it is not suitable for the general web.

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