【问题标题】:javascript correct way to self-reference variables of a function during initializationjavascript在初始化期间自引用函数变量的正确方法
【发布时间】:2015-05-27 19:09:51
【问题描述】:

以下工作并满足我的需要。但是,有没有更好的方法来引用“c:”中的“a”和“b”?

<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>

【问题讨论】:

  • 我总是这样做 this.athis.b
  • 另外,如果它重要的话,idk,但如果你有一个方便的方法,而不是用新对象破坏 Foo.prototype,你可能想要使用 extend() 或 mixin() 方法。
  • 那么,您需要什么?它应该如何与继承一起工作?你为什么要把数据属性放在原型上?
  • 看来我把这个问题搞砸了。问题是当函数被实例化为匿名函数时。在这种情况下,没有定义“this”。谢谢大家,但要关闭它。

标签: javascript variables initialization self-reference


【解决方案1】:
c: function() {
  return this.a + this.b;
}

【讨论】:

  • 这不等于... (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... 这取决于你想如何使用 Foo.prototype.c路...
【解决方案2】:

当你创建一个Foo的新对象时,构造函数中的属性和通过原型添加的属性都可以被访问,在对象上下文范围内,带有this字样。

(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

有关原型如何工作的更多信息,请查看以下内容: How does JavaScript .prototype work?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-22
    • 1970-01-01
    相关资源
    最近更新 更多