javascript - 'var' 声明的变量和 'this' 在 Javascript 中创建的属性有什么区别?

标签 javascript

首先使用var

 function testCode(some) 
    {
         var something = some;
    }

第二次使用这个

function testCode2(some) 
{
     this.something = some ;
}

最佳答案

在第一个函数中,something 是一个private(局部)变量,这意味着它在函数外是完全不可访问的;而在第二个中,它是一个 public 实例变量。设置变量的上下文将取决于您调用函数的方式:

> testCode2("foo"); // this will refer to document.window
> something
"foo"

>> var obj = new testCode2("foo"); // this will refer to the new object
>> something
ReferenceError: something is not defined
>> obj.something
"foo"

引用:

关于javascript - 'var' 声明的变量和 'this' 在 Javascript 中创建的属性有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12094676/

相关文章:

javascript - 使用 JavaScript 添加带有现有函数的 onclick 监听器

c# - C# 的类似 V8 的哈希表?

javascript - 从 ajax jquery post 响应中获取 <h2> 元素内的文本

javascript - 如何使用 Lodash 从数组中删除对象?

javascript - 将 JavaScript 传递给 Session 变量

javascript - YouTube API - 获取下一个相关视频

javascript - 使用带有 React 的 ES6 样式语法在浏览器中导入 JSON 文件

javascript - 如果 URL 后面有查询字符串,则使用 javascript 更改文件扩展名

javascript - 按钮在屏幕底部淡入

javascript - Cookie 不是使用 ngCookies 存储的