Javascript对象:文字与构造函数 [英] Javascript Object : Literal Vs Constructor

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

问题描述

为了创建Javascript对象,我们可以使用Literal或者Constructor方式;
以构造函数的方式,我们说;

For creating Javascript object, we can use Literal or Constructor way; In Constructor way, we say;

function myObj(){
this.myProp1 = "abc";
this.myProp2 = "xyz";
}

以字面的方式,我们说;

In literal way, we say;

var myObj = {
myProp1:"abc",
myProp2:"xyz",
}

我的问题是在声明属性的时候,为什么会有区别,为什么我们在构造函数的时候使用this.myProp1而不是在Literal方式中使用this?

My question is when declaring properties, why there is a difference like why do we use "this.myProp1" in case of Constructor way and not use "this" in Literal way ?

推荐答案

当直接定义某个对象时,对象直接构建在代码中。它尚未完成,直到它完成。在那个时候,这个没有任何意义(不是说它也不需要)。

When defining something literally, the object is being built directly in the code. It doesn't exist yet until it is complete. At that point, this would have no meaning (not that there is any need for it either).

要在对象创建函数中理解这一点,首先认识到 this 在JavaScript中是特殊的。每当你调用一个函数时,你都可以传递任何你想要的 this 。一般来说,事件处理程序等事件都会将引发事件的DOM对象作为这个传递。在你的代码中,你可以这样做: MyFunction.call(whatever_needs_to_be_this [,param0,param1]); 。当你使用new运算符,如 var mything = new SomeThing(); 时,JavaScript本质上是这样做的:

To understand this in the object creation function, first realize that this is special in JavaScript. Whenever you call a function, you can pass anything you want to be this. In general, things like event handlers will pass the event-causing DOM object to be passed as this. In your code, you do this as: MyFunction.call(whatever_needs_to_be_this[, param0, param1]);. When you use the new operator, such as var mything = new SomeThing();, JavaScript is essentially doing something like:

var mything = {};
SomeThing.call(mything);

这个在这种情况下将会是 mything 在你的函数中。

this in this case is going to be mything in your function.

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

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