简体   繁体   English

以下 javascript 代码的输出是什么,为什么?

[英]What is the output of the following javascript code and why?

I am really new in JavaScript.我真的是 JavaScript 新手。 Can you please explain what should be the output of the following JavaScript Code?你能解释一下以下 JavaScript 代码的输出应该是什么吗? Please explain the reason as detail as possible.请尽可能详细地说明原因。 Thank you so much.非常感谢。

var Foo = function( a ) { 
    function bar() {   
        return a; 
    }
    this.baz = function() {   
        return a; 
    };
};

Foo.prototype = {
    biz: function() {    
        return a; 
    }        
};

var f = new Foo( 7 );
f.bar(); 
f.baz(); 
f.biz(); 

The result is an error.结果是错误。 f.bar is not a function. f.bar 不是函数。 That is because it is a local function with scope only within the Foo function.那是因为它是一个局部函数,其作用域仅在 Foo 函数内。 It is effectively a private function only available within the function it is defined in.它实际上是一个私有函数,仅在定义它的函数中可用。

When you call new Foo(), you are invoking the function as a constructor.当您调用 new Foo() 时,您正在调用该函数作为构造函数。 This will create an object and return it.这将创建一个对象并返回它。 Within the function that object can be referenced as 'this'.在函数中,该对象可以被引用为“this”。 Since baz is added as a property to the this object, it will be included in the object created when you do f = new Foo(7) .由于baz作为属性添加到this对象,它将包含在您执行f = new Foo(7)时创建的对象中。

baz is available since it is part of the constructed object when you do new Foo(). baz 是可用的,因为当你执行 new Foo() 时它是构造对象的一部分。

f.biz() is also available since it is placed in Foo's prototype. f.biz() 也可用,因为它位于 Foo 的原型中。 Adding a prototype meaning it is shared by all instances of Foo (f being one of them).添加一个原型意味着它被 Foo 的所有实例共享(f 是其中之一)。

The variable a is only defined within the constructor function, so it will be undefined in the biz() function call.变量 a 仅在构造函数中定义,因此在 biz() 函数调用中未定义。 Consequently, f.biz() will return undefined .因此, f.biz() 将返回undefined

Not only will this throw an error since f.bar() is only accessible inside the Foo function scope (eg its basically a "private" method), but also all of the methods (bar, baz, biz) reference the property "a" which isnt actually defined as a property of Foo instances.这不仅会抛出错误,因为 f.bar() 只能Foo 函数范围内访问(例如,它基本上是一个“私有”方法),而且所有方法(bar、baz、biz)都引用了属性“a " 这实际上并未定义为 Foo 实例的属性。

You should be storing "a" inside Foo using this.a = a , and accessing it inside your Foo methods (bar, baz, biz) using return this.a您应该使用this.a = a在 Foo 中存储“a”,并使用return this.a在您的 Foo 方法(bar、baz、biz)中访问它

you can do as below.你可以做如下。

 var Foo = function( a ) { this.a = a; this.bar = function() { return this.a; } this.baz = function() { return this.a; }; }; Foo.prototype = { biz: function() { return this.a; } }; var f = new Foo( 7 ); console.log(f.bar()); console.log(f.baz()); console.log(f.biz());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM