Objects in JavaScript (part I)

來源:互聯網
上載者:User

http://dmitry.baranovskiy.com/

Recently I was talking to friend of mine about objects in JavaScript. He is writing JavaScript for living and very good at it, however I found that he doesn’t understand some core features of the language. So, in case you have this gap in understanding JavaScript, I’ll try to explain.

Friend of mine give cite me one book:

“The interesting thing about ECMAScript primitive values for Booleans, numbers, and strings is that they are pseudo-objects, meaning that they actually have properties and methods.”

I am really sorry, but this doesn’t make any sense.

First lets take a look at this example:

var a = 5;a.t = 3;alert(a.t);

It will alert “undefined”. Why? If “a” is a “pseudo-object” then why it doesn’t keep my property? The thing is, “a” is not an object. Not even “pseudo-object”. It is primitive number. It doesn’t have properties. As you know JavaScript convert variable from one type to another on the fly:

var b = "w" + a + [1, 2, 3];

In this example number “a” and array [1, 2, 3] will be converted to string on the fly. The same is happening with anything before “.” operator, JavaScript simply converts left hand side parameter to object. So, at the second line of the example JavaScript creates new object Number with value equals to “a” (5 in our case), then create new property “t” with value 3. But then this object is not assigned back to variable “a”, it is just disappear in garbage. Third line will again create new object and will try to read it property “t”, which is undefined.

Primitive types like boolean, number and strings are not objects, they could be converted to objects. What the rule? JavaScript has six built-in types: null, undefined, number, string, boolean and object. The conversion rule is simple: if input is object, leave it as is; if input is null or undefined, throw an exception; otherwise create new object (new Number(input) or new String(input) ornew Boolean(input)). Hope this small bit will help somebody to understand objects in JavaScript a bit better. Next type I write about prototype and friends. 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.