oop - Class vs. static method in JavaScript -
i know work:
function foo() {}; foo.prototype.talk = function () { alert('hello~\n'); }; var = new foo; a.talk(); // 'hello~\n'
but if want call
foo.talk() // not work foo.prototype.talk() // works correctly
i find methods make foo.talk
work,
foo.__proto__ = foo.prototype
foo.talk = foo.prototype.talk
is there other ways this? don’t know whether right so. use class methods or static methods in javascript code?
first off, remember javascript prototypal language, rather class-based language1. foo
isn't class, it's function, object. can instantiate object from function using new
keyword allow create similar class in standard oop language.
i'd suggest ignoring __proto__
of time because has poor cross browser support, , instead focus on learning how prototype
works.
if have instance of object created function2 , access 1 of members (methods, attributes, properties, constants etc) in way, access flow down prototype hierarchy until either (a) finds member, or (b) doesn't find prototype.
the hierarchy starts on object called, , searches it's prototype object. if prototype object has prototype, repeats, if no prototype exists, undefined
returned.
for example:
foo = {bar: 'baz'}; alert(foo.bar); //alerts "baz" foo = {}; alert(foo.bar); //alerts undefined function foo(){} foo.prototype = {bar: 'baz'}; f = new foo(); alert(f.bar); //alerts "baz" because object f doesn't have attribute "bar" //so checks prototype f.bar = 'buzz'; alert( f.bar ); //alerts "buzz" because f has attribute "bar" set
it looks me you've @ least understood these "basic" parts already, need make them explicit sure.
in javascript, object3.
everything object.
function foo(){}
doesn't define new function, defines new function object can accessed using foo
.
this why can access foo
's prototype foo.prototype
.
what can set more functions on foo
:
foo.talk = function () { alert('hello world!'); };
this new function can accessed using:
foo.talk();
i hope you're noticing similarity between functions on function object , static method.
think of f = new foo();
creating class instance, foo.prototype.bar = function(){...}
defining shared method class, , foo.baz = function(){...}
defining public static method class.
1: class
"future reserved word" in ecmascript 5 specification, es6 introduces ability define classes using class
keyword.
2: class instance created constructor, there many nuanced differences don't want mislead you
3: primitive values—which include undefined
, null
, booleans, numbers, , strings—aren't technically objects because they're low-level language implementations. booleans, numbers, , strings still interact prototype chain though objects, purposes of answer, it's easier consider them "objects" though they're not quite.
Comments
Post a Comment