Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
966 views
in Technique[技术] by (71.8m points)

oop - Why are JavaScript Primitive-Variables immutable and Object-Variables not?

There is a way to add a member-function or member-property to Number, String, ect...-Variables with the help of the prototype-property:

 Number.prototype.member = function(){ console.log('number-member-function called'); };

or with help of the proto-property of the variables themselves:

 var num = 7;
 num.__proto__.member = function(){ console.log('number-member-function called'); };

Just like to any other kind of JavaScript-types. But what is the difference of the implementation of Primtives and Objects in JavaScript so that the code below does not work for Numbers but for Objects?

 var num = 7;
 num.member = function(){ console.log('number-member-function called'); };
 num.member(); // TypeError: num.member is not a function

 var obj = {};
 obj.member = function(){ console.log('object-member-function called'); };
 obj.member(); // object-member-function called

Does anybody know approximatly how JavaScript Primitves and Objects are implemented under the hood? Because all JavaScript-implementations in all browsers must be done identically or almost for there is an error thrown with the Number-Function called member.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When you use the literal notation for the boolean, string and number types, the constructors (Boolean, String, Number) are not used. The primitive types still behaves almost like they had been instantiated with the new operator, but are truly primitive types.

Only when you are trying to use them as objects or you are trying to use a property of a constructor, the JavaScript interpreter creates a wrapper object around them behind the scenes. After this, the wrapper objects gets discarded and you are dealing again with the primitive type. So:

var num = 7; //primitive

// You are trying to use num as an object: a wrapper object gets created and discarded just after the assignment
num.member = function(){ console.log('number-member-function called'); }; 

// This will throw an error, because here num is primitive again (member was defined on the discarded wrapper)
num.member();

More on this topic can be found on the book "JavaScript Enlightenment" by Cody Lindley, based on the ECMA-262, Edition 3 specification.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...