javascript中的对象和函数 [英] Objects and functions in javascript

查看:105
本文介绍了javascript中的对象和函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

Javascript:我是否需要为对象中的每个变量都放置this.var?

我很难理解javascript中的函数和对象。据说功能也是对象,对象是一种关联数组,即键值对的集合。我明白如果我写

I'm struggling to understand functions and objects in javascript. It is said that also functions are objects and objects are kind of "associative arrays" i.e. collections of key-value pairs. I understand that if I write

function myFunction() {
    var value = 0;
}
alert(myFunction.value); //then this gives me "undefined"

因为变量有函数范围。但如果我写

because variables have function scope. But if I write

function myFunction() {
    this.value = 0;
}
alert(myFunction.value); //then this gives me "undefined" too.

但最后,如果我写

function myFunction() {
    this.value = 0;
}
myFunction.value = 0;
alert(myFunction.value); //then this gives me 0

所以我可以给myFunction属性value但是来自outside 。有人可以解释发生了什么以及为什么this.value = 0;不会创建属性值。

So I can give myFunction property "value" but from "outside". Can someone explain what is going on and why this.value = 0; doesnt create property "value".

推荐答案

让我们分别看看所有三种情况:

Let's look at all three cases individually:

function myFunction()
{
    var value = 0;
}

在这里,你要在函数的范围内声明一个变量。每次调用该函数时,都将创建该变量(并将分配内存)。当函数返回时,变量超出范围 - 变量被标记并将被GC。无法从范围higher访问范围而不是此函数的范围...如果此函数在其范围内定义了一个函数,则该函数将可以访问变量 value (查看闭包以获取更多详细信息)。底线:变量仅在调用函数时存在,并且在函数返回后不存在。

Here, you're declaring a variable in the function's scope. Each time the function is called, the variable will be created (and memory will be allocated). When the function returns, the variable goes out of scope - the variable value is flagged and will be GC'ed. The scope can't be accessed from a scope "higher" than this function's scope... if this function defined a function within its scope, that function will have access to the variable value (look into closures for more details). Bottom line: the variable only exists as when the function is called, and won't exist after the function returns.

function myFunction()
{
    this.value = 0;
}

在这里,你要定义一个可能是构造函数的函数,一个方法,事件处理程序或以上所有的组合。 是一个引用,它将指向调用该函数的上下文。此上下文是ad hoc确定的,可能会有所不同:

Here, you're defining a function that could be a constructor, a method, an event handler or a combination of all of the above. this is a reference that will point to the context in which the function is called. This contexted is determined "ad hoc" and may vary:

myFunction();// global scope, this points to window
var anObject = {method: myFunction};
anObject.method();//called in the object's context, this points to object
console.log(abObject.value);//logs 0
var instance = new myFunction();//as constructor
console.log(instance.value);//logs 0
document.getElementById('anInputField').onclick = myFunction;//on click, value will be set to 0

在最后一种情况下:

function myFunction()
{
    this.value = 0;
}
myFunction.value = 0;

如果你写完这篇文章,那就没有任何区别了:

It wouldn't have made any difference if you'd have written this:

function myFunction()
{}
myFunction.value = 0;

因为,正如我上面所解释的那样:这个引用函数调用时的上下文。这不一定是 myFunction ,事实上:通常不会是:

Because, as I explained above: this references whatever the context is at the time the function is called. This needn't be myFunction, in fact: more often than not it won't be:

var anObject = {method: myFunction};
myFunction.value = 101;//myFunction.value is changed
anObject.method();
console.log(anObject.value);//0 -> the function still sets the value property to 0

如果要访问该函数内的函数属性,最简单的方法是像任何其他对象一样引用该函数:

If you want to access a function's properties inside that function, the easiest way is to reference that function like any other object:

function myFunction()
{
    this.value = myFunction.value;
}
myFunction.value = 101;

警告:

只是一个友善的警告:在函数中使用 this 而不检查全局变量是不安全的......如果在没有显式上下文的情况下调用函数,JS使用全局( window )默认情况下对象 。这意味着将属性分配给任何对象的每一行恰好也指向一个全局变量:

Caution:
Just a friendly warning: it's not very safe to use this in functions without checking for globals... If a function is called without an explicit context, JS uses the global (window) object by default. This means that every line that assigns a property to whatever object this happens to be pointing too will set a global variable:

function myFunction()
{
    this.foo = 'bar';
}
myFunction();
console.log(window.foo);//logs bar EVIL GLOBAL

一些防止全局对象被全局变量混乱的方法:

A few ways to prevent the global object from being cluttered with globals:

function mySafeFunction()
{
    'use strict';//throws errors, check MDN
    //this defaults to null, instead of window
    impliedGlobal = 'Error';//doesn't work
    this.onGlobal = 'Error';//null.property doesn't work
}
//same goes for constructors, but a more precise check can be used, too (and works on older browsers)
function SafeConstructor()
{
    if (!(this instanceof SafeConstructor))
    {//this doesn't point to SafeConstructor if new keyword wasn't used
        throw new Error('Constructor wasn\'t called with new keyword');
        //or "correct" the error:
        return new SafeConstructor();
    }
    console.log(this);// will always point to the SafeConstructor object
}

这篇关于javascript中的对象和函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆