简体   繁体   English

Javascript创建对象结构

[英]Javascript create object structure

I used to write a lot of Javascript, and now I'm just jumping back into it, but it seems like I have lost my mind. 我曾经写过很多Javascript,现在我只是跳回去,但是似乎我已经失去了理智。 I'm trying to create an object using function, and I am doing it just the same way that my online searches suggest I should do. 我正在尝试使用函数创建对象,并且这样做的方式与我的在线搜索建议的方式相同。 I created this example to show the many ways I have tried. 我创建了这个示例,以展示我尝试过的许多方法。

<script>
function a(){
    function b(){};
    this.c = function(){};
    this.d = 0;
    var e = function(){};
    var f = 0;
}
a.g = function(){};
a.prototype.h = function(){};

var a2 = function(){
    function b(){};
    this.c = function(){};
    this.d = 0;
    var e = function(){};
    var f = 0;
}
a2.g = function(){};
a2.prototype.h = function(){};
</script> 

From what I remember, I should be able to call ab() , ac() , and ad , and likewise for a2 . 根据我的记忆,我应该能够调用ab()ac()ad ,同样可以调用a2

However, when I try to call them, it doesn't work. 但是,当我尝试给他们打电话时,它不起作用。 When I type the variable name in the console, it doesn't even show them as being an option. 当我在控制台中键入变量名时,它甚至都没有将它们显示为选项。 I can however call ag() . 但是我可以调用ag() I can't call ah() , but I can call a.prototype.h() . 我不能调用ah() ,但是我可以调用a.prototype.h()

I tried this in chrome, and a few things as well in both firefox and Safari. 我在chrome中尝试过此操作,在Firefox和Safari中也尝试了一些操作。

As far as I can tell from online tutorials, this is not interacting the way I should be expecting it to. 据我从在线教程中了解到的,这并没有像我期望的那样相互作用。

b , e and f are variables in the scope of the function a . bef是函数a范围内的变量。 They are never exposed outside that function. 它们永远不会暴露在该功能之外。

c and d are assigned, when a is called, to whatever this is. cd分配, a被调用,以什么this是。 If you call new a() then it will be the instance of a that is returned. 如果调用new a() ,则将返回a的实例。

g is a property of a directly, so you can call it. g是a a直接属性,因此可以调用它。

h is on the prototype chain so it will appear, like c and d , on instances of a created with new . h是原型链所以它会出现,比如cd上的实例a与创建new

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

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