mirror of
https://github.com/flynx/Course-JavaScript.git
synced 2025-10-29 11:00:10 +00:00
Compare commits
2 Commits
8209790c8d
...
98eedb02bc
| Author | SHA1 | Date | |
|---|---|---|---|
| 98eedb02bc | |||
| ea39e3d0c3 |
@ -119,6 +119,7 @@
|
||||
|
||||
// Prototypes and inheritance
|
||||
//
|
||||
// XXX
|
||||
|
||||
var a = {
|
||||
}
|
||||
@ -131,6 +132,14 @@
|
||||
|
||||
|
||||
// Constructors
|
||||
//
|
||||
// A constructor is simply a function that "constructs" or populates an
|
||||
// object.
|
||||
//
|
||||
// By convention constructor functions are capitalized (Pascal-case)
|
||||
//
|
||||
// Classic constructors are called with a "new" keyword which creates a
|
||||
// bare instance and passes it to the function as the call context.
|
||||
//
|
||||
|
||||
function A(){
|
||||
@ -146,7 +155,12 @@
|
||||
__proto__: A.prototype,
|
||||
}
|
||||
|
||||
// XXX a safer way -- now we can forget new...
|
||||
//
|
||||
// The problem with the default way this is done is that now a
|
||||
// constructor will behave differently when called directly or if called
|
||||
// via the new syntax. This can be desirable in some cases but in
|
||||
// general this is a pitfall, so let's unify the two cases:
|
||||
//
|
||||
|
||||
function B(){
|
||||
var obj = {
|
||||
@ -155,10 +169,10 @@
|
||||
return obj
|
||||
}
|
||||
|
||||
// this can be calles with and withot new
|
||||
// this can be called with and without new:
|
||||
var z = B()
|
||||
|
||||
// less naive...
|
||||
// less naive -- reuses the instance created by new...
|
||||
function C(){
|
||||
var obj = this instanceof C ?
|
||||
this
|
||||
@ -168,6 +182,11 @@
|
||||
// make C instances related to B...
|
||||
C.prototype.__proto__ = B.prototype
|
||||
|
||||
//
|
||||
// Note that constructor extension is trivial if you think of how
|
||||
// prototypical inheritance works, to link A and B "instances" all we
|
||||
// needed to do is link the constructor prototypes in the code above.
|
||||
//
|
||||
|
||||
|
||||
// Extending builtin types
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user