简体   繁体   English

为什么我需要在我的javascript方法中添加单词this

[英]Why Do I need to add the word this to my javascript method

I know this is kind of a silly example-- but why does this code result in an error that bar is not defined. 我知道这是一个愚蠢的示例-但是为什么此代码会导致未定义bar的错误。 Wouldn't javascript look to see if bar was a property of "this" object. javascript不会查看bar是否为“ this”对象的属性。 I know that adding this, fixes the problem-- but this tends to throw me off. 我知道添加此操作可以解决问题-但这会使我失望。 In other programming languages (C#) for instance, this is usually redundant-- why does it need to be added in the code below? 例如,在其他编程语言(C#)中,这通常是多余的-为什么需要在下面的代码中添加它?

   var myObject = {
        foo : function(){
            alert(bar);
        },
        bar : "hello world"
    };

    myObject.foo();

http://jsfiddle.net/Mv86n/ http://jsfiddle.net/Mv86n/

Wouldn't javascript look to see if bar was a property of "this" object javascript不会查看bar是否为“ this”对象的属性

No. It looks at what variables are in scope, not what properties are members of the current context. 不。它查看范围内的变量,而不是当前上下文成员的属性。

Javascript has function scope, not object scope. JavaScript具有功能范围,而不是对象范围。

Only identifiers declared within the same function is in the local scope, everything else is accessed from the global scope. 只有在同一函数中声明的标识符在本地范围内,其他所有内容都可以从全局范围访问。

It just doesn't work that way. 就是那样行不通。 It could have, but the language designers probably thought that that way would lead to inefficiencies, ambiguities and code that it hard to see what is going on. 可能有,但是语言设计人员可能认为,这种方式会导致效率低下,模棱两可和代码混乱,很难看到正在发生的事情。

I'll admit that I am also sometimes annoyed by the necessity of prepending "this." 我承认有时有时还会在前面加上“ this”,这让我很烦。 onto things, and even more annoyed that I am constantly having to say "var self = this;", but such is life in Javascript. 到事物上,甚至更让我烦恼的是,我经常不得不说“ var self = this;”,但这就是Java语言中的生活。 You just have to accept it for what it is, and move on. 您只需要接受它的实质,然后继续前进即可。

Think of it this way: 这样想:

var myObject = {
    foo : null,
    bar : "hello world"
};
myObject.foo = function(){
    alert(bar);
}

Now, what is bar supposed to refer to? 现在, bar应该指的是什么? As you can see more easily now, bar is not in scope. 如您现在更容易看到的, bar不在范围内。

In C#, methods belong to objects and it is known what attributes they have, which is why such a thing is possible. 在C#中,方法属于对象,并且知道它们具有什么属性,这就是为什么这种事情可行的原因。 But in JavaScript, you don't have that knowledge, "methods" don't belong and attributes are dynamic, which makes such scoping rules unfeasible. 但是在JavaScript中,您没有知识,“方法”不属于属性,并且属性是动态的,这使得这种范围界定规则不可行。

In javascript, the lookup priority is ancestor functions scopes (which can be nested, unlike in C++ and Java) from the nearest of the code beiing executed to the farthest. 在javascript中,查找优先级是从执行的最接近代码到最远的代码(与C ++和Java不同,可以嵌套)的祖先函数范围。

On that trivial example, it looks like having an implicit this would make sense, but it would be much more complicated to specify and used with different levels of nested functions and object. 在这个简单的示例上,看起来隐式的this做似乎是有道理的,但是指定和与不同级别的嵌套函数和对象一起使用将更加复杂。

(function() {
    var myVar = "dsjsh";
    return {
        myVar: "var",
        myMethod: function() {
            /* which */ myVar;
        };
    }
})()

Obviously, the language made the choice of simplicity (at least for this matter). 显然,该语言选择了简单性(至少就此而言)。

JavaScript doesn't exactly have a concept of classes or class scope ; JavaScript并不完全具有类范围的概念; myObject should be thought of as a map, moreso than an object. myObject应该被认为是地图,而不是对象。 For example, you could do this: 例如,您可以这样做:

function foo() {
    alert(this.bar);
}
var myObject = {
    bar: "hello world"
};
myObject.foo = foo;

In this case, why should foo know about myObject when it's defined? 在这种情况下,为什么在定义myObjectfoo应该知道它? When you call myObject.foo() , JavaScript passes in myObject as this (of course, JavaScript's scoping rules regarding this are kind of strange, so this isn't always what you think it is), and you can access myObject through this . 当您调用myObject.foo() ,JavaScript会以this传入myObject (当然,JavaScript与此相关的作用域规则有点奇怪,因此this并不总是您认为的那样),并且可以通过this来访问myObject If you just called foo() , this would be something different (in a browser, it would probably be window ), and even accessing this.bar wouldn't work. 如果您只是调用foo()this可能会有所不同(在浏览器中,可能是window ),甚至无法访问this.bar

暂无
暂无

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

相关问题 Javascript:对象方法 - 为什么需要括号? - Javascript: Object method - why do I need parentheses? 我需要使用 javascript 将库添加到我的项目中 - I need to add library to my project with javascript 我需要添加什么,所以我的JavaScript会像我想要的那样工作? - What do i need to add, so my JavaScript would work as i want it to? 我需要在我的网络服务器上安装javascript吗? - Do I need to install javascript on my webserver? 当我想获得第一个孩子时,为什么需要在我的childNodes数组中添加索引1? - Why do I need to add index 1 to my childNodes array, when I want to get the first child? 为什么在Javascript中使用字符串替换时需要添加/ g? - Why do i need to add /g when using string replace in Javascript? TypeScript 和 Redux:为什么要加`| undefined` 到我的 Reducer state 类型? - TypeScript and Redux: Why do I need to add ` | undefined` to my Reducer state type? 为什么我不需要在我的 html 文件中引用相对路径来加载带有 express js 的 javascript 文件? - Why do I not need to reference the relative path in my html file to load a javascript file with express js? 我需要向我的 Javascript 添加什么才能显示来自我的 DynamoDB 表和 API 网关的命中计数器? - What do I need to add to my Javascript to be able to show the hit counter from my DynamoDB table and API Gateway? 如何在 html 中异步添加我的 javascript SDK 并在准备好后调用 initialize 方法? - How do I asynchronously add my javascript SDK in html and call initialize method once ready?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM