Demystifying Prototypes

Post on 15-May-2015

10.666 views 1 download

Tags:

Transcript of Demystifying Prototypes

typesDemystifyingProto...........

types

undefined numbernull

boolean objectstring

undefined numbernull

boolean objectstring

b.name

b[“name”]

“a” in b

for (var i in b) …

b.hasOwnProperty(“a”)

b instanceof d

function f() {};

f();new f;

function

function f() {};

f();new f;

function

function f() {};

f();new f;

function

ObjectNumberStringBooleanFunctionArrayRegExpDate

A

function A() {};

A

function A() {};

constructor: A

A

b

function A() {};

constructor: A

var b = new A;

A

b

x: 1

function A() {};

constructor: A

var b = new A;A.prototype.x = 1;

A

b

x: 1

y: 2

function A() {};

constructor: A

var b = new A;A.prototype.x = 1;b.y = 2;

A

bc

x: 1

y: 2

function A() {};

constructor: A

var b = new A;A.prototype.x = 1;b.y = 2;var c = new A;

A

bc

x: 1

y: 2

function A() {};

constructor: A

var b = new A;A.prototype.x = 1;b.y = 2;var c = new A;A.prototype = {v: 1, w: 2};

A

bc

x: 1

y: 2

v: 1w: 2

function A() {};

constructor: A

var b = new A;A.prototype.x = 1;b.y = 2;var c = new A;A.prototype = {v: 1, w: 2};

A

bc

x: 1

y: 2d

v: 1w: 2

function A() {};

constructor: A

var b = new A;A.prototype.x = 1;b.y = 2;var c = new A;A.prototype = {v: 1, w: 2};var d = new A;

A P

bc

x: 1

y: 2d

v: 1w: 2

constructor: A

P.hasOwnProperty(“constructor”)“constructor” in cfor (var i in P) alert(i);c.constructorc instanceof Ad instanceof Ad.constructor

null

d

A

Object

c

function A() {};function B() {};B.prototype = new A;var d = new B;

null

d

A

Object

B

null

d

A

Object

B

function A() {…};function B() {};var Z = function () {};Z.prototype = A.prototype;B.prototype = new Z;var d = new B;

null

d

A

Object

B

function A() {…};function B() {};var Z = function () {};Z.prototype = A.prototype;B.prototype = new Z;var d = new B;

Z

goog.inherits = function(childCtor, parentCtor) { /** @constructor */ function tempCtor() {}; tempCtor.prototype = parentCtor.prototype; childCtor.superClass_ = parentCtor.prototype; childCtor.prototype = new tempCtor(); childCtor.prototype.constructor = childCtor;};

exports.inherits = function(ctor, superCtor) { ctor.super_ = superCtor; ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false } });};

null

A

Function

Object

null

A

Function

Object

Function.constructor === Function

JavaScript Paradox

Thank You

dmitry@baranovskiy.com