0

The following works and does what I need. However, is there a better way to reference "a" and "b" in "c:"?

<html>
<head>
    <script type="text/javascript">
        var bar;

        function Foo() {}
        Foo.prototype = {
            a: 1,
            b: 2,
            c: function() {
                return Foo.prototype.a + Foo.prototype.b;
            }
        }

        bar = new Foo();

        console.log('c is: ' + bar.c());
    </script>
</head>
<body>
    <button onclick="document.write('c is: ' + bar.c())">Try it</button>
</body>
</html>
candr
  • 1
  • 1
    I always do `this.a` and `this.b` – xdhmoore May 27 '15 at 19:12
  • Also, idk if it matters, but you might want to use an extend() or mixin() method if you have one handy instead of clobbering Foo.prototype with a new object. – xdhmoore May 27 '15 at 19:13
  • 1
    So, what do you need? How should it work with inheritance? Why do you put data properties on the prototype at all? – Bergi May 27 '15 at 19:41
  • possible duplicate of [Javascript: Object Literal reference in own key's function instead of 'this'](http://stackoverflow.com/q/10711064/1048572) – Bergi May 27 '15 at 19:44
  • 1
    Seems I screwed up this question. The problem was when the function was being instantiated as an anonymous function. In that case, "this" isn't defined. Thanks all but closing this out. – candr May 27 '15 at 20:21
  • Don't use `Foo.prototype = {/* whatever */}`, extend prototype by assignment. This way you kill default `prototype` created by engine along with the non-enumerable `constructor` property. –  May 27 '15 at 21:23

2 Answers2

0
c: function() {
  return this.a + this.b;
}
ChadF
  • 1,750
  • 10
  • 22
  • This is not equal... (function(){return this.a + this.b;}).call({a:4, b:5}) = 9, (function(){return Foo.prototype.a + Foo.prototype.b;}).call({a:4, b:5}) = 3... it depends on how you want to use Foo.prototype.c down the road... – Pete May 27 '15 at 19:36
0

When you create a new object of Foo, the properties in the constructor function and the ones added through the prototype can be access, in the objects context scope with the this word.

(function() {
    var bar;

    function Foo() {
        //Constructor function properties and methods
    }

    //Protoytpe methods and properties
    Foo.prototype = {
        a: 1,
        b: 2,
        c: function() {
            return this.a + this.b;
        }
    }

    bar = new Foo();
    console.log('c is: ' + bar.c());

})();  

Jsfiddle

For more info on how the prototype works, check this out: How does JavaScript .prototype work?

Community
  • 1
  • 1
andybeli
  • 836
  • 7
  • 14