Prototype source code analysis-object Part 1)

Source: Internet
Author: User

The previous day, I analyzed the prototype function. Today, the prototype object part is started.
It should be noted that the object part is a little different from the previous function part. This time, the object is directly extended on the object, not the object. prototype, the two are essentially different, that is, the extension of this obeject is equivalent to adding a static variable (method) of the object );

extend(Object, {})
Object.extend(Function.prototype,{})

 

There are many object methods, some of which are very basic (such as type Judgment), so I don't want to analyze them all. I just want to pick a few important or hard to understand:

  extend(Object, {
extend: extend,
inspect: inspect,
toJSON: NATIVE_JSON_STRINGIFY_SUPPORT ? stringify : toJSON,
toQueryString: toQueryString,
toHTML: toHTML,
keys: Object.keys || keys,
values: values,
clone: clone,
isElement: isElement,
isArray: isArray,
isHash: isHash,
isFunction: isFunction,
isString: isString,
isNumber: isNumber,
isDate: isDate,
isUndefined: isUndefined
});

The first and most important method is the extend method, which is available in many books and is basically the same. It is a method for copying attributes.

This method is used to add attributes later (including function. Prototype.

One instance:

Now there are two objects:

    var obj_1 = {
name : 'xesam'
};
var obj_2 = {
age : '24',
name: 'xesam_1'
};

Now I want to merge the attributes of these two objects into one object.
There are two implementation methods:
First, create an empty object and copy the two objects to it (this corresponds to the clone method in prototype, but Clone requires an object)
Second, copy the properties of obj_2 to obj_1.
In fact, the above two methods do not need to be clearly identified, because the corresponding methods are the same.
If you do not consider deep copy and duplicate attributes, the implementation is very simple, for example:

(Function (){
Return;
VaR obj_1 = {
Name: 'xesam'
};
VaR obj_2 = {
Age: '24 ',
Name: 'xesam _ 1'
};
Function extend (destination, source ){
For (VAR property in source ){
Destination [property] = source [property];
}
Return destination;
}
Extend (obj_1, obj_2 );
Console. Log (obj_1); // change name to xesam_1
})();

If you look at the prototype source code, you will find that this product is actually doing so. Compared with jquery's implementation, it is simply weak.

Aside from the prototype application environment and the purpose of doing so, if this implementation is used in common use, the problem will be,
First, what if there are two identical attributes?
Second, the results returned by the in operation in different browsers may be inconsistent.

According to the above implementation, the attribute in source will overwrite the attribute with the same name in destination. If this is not our intention, we can simply change the code:

(Function (){
Return;
VaR obj_1 = {
Name: 'xesam'
};
VaR obj_2 = {
Age: '24 ',
Name: 'xesam _ 1'
};
Function extend (destination, source ){
For (VAR property in source ){
If (destination. hasownproperty [property]) {
Destination [property] = source [property];
}
}
Return destination;
}
Extend (obj_1, obj_2 );
Console. Log (obj_1); // name or xesam
})();

Therefore, we can add another parameter overwrite to implement more flexible configuration. By the way, let's review the function part's wrap method.

<! Doctype HTML public "-// W3C // dtd xhtml 1.0 transitional // en"
Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd>
<HTML>
<Head>
<Meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8"/>
<Title> </title>

</Head>
<Body>
<SCRIPT type = "text/JavaScript">
Function. Prototype. Bind = function (context ){
VaR _ method = This, argS = array. Prototype. Slice. Call (arguments, 1 );
Return function (){
VaR B = args. Concat (array. Prototype. Slice. Call (arguments, 0 ));
Return _ method. Apply (context, B );
}
}
Function. Prototype. Wrap = function (wrapper ){
VaR _ this = this;
Return function (){
VaR Params = [_ this. BIND (this)]. Concat (array. Prototype. Slice. Call (arguments, 0 ));
Wrapper. Apply (this, Params );
}
}
Function extend (destination, source, overwrite ){
For (VAR property in source ){
If (overwrite ){
Destination [property] = source [property];
} Else if (destination. hasownproperty [property]) {
Destination [property] = source [property];
}
}
Return destination;
}
Object. Prototype. Extend = extend. Wrap (function (process, source, overwrite ){
If (overwrite | false ){
Process (this, source, true );
} Else {
Process (this, source, false );
}
});
(Function (){
VaR obj_1 = {
Name: 'xesam'
};
VaR obj_2 = {
Age: '24 ',
Name: 'xesam _ 1'
};
Obj_1.extend (obj_2); // The Name Of obj_1 is not rewritten.
Console. Log (obj_1 );
})();
(Function (){
VaR obj_1 = {
Name: 'xesam'
};
VaR obj_2 = {
Age: '24 ',
Name: 'xesam _ 1'
};
Obj_1.extend (obj_2, true); // rewrite the name of obj_1
Console. Log (obj_1 );
})();
</SCRIPT>
</Body>
</Html>

[Note: this call method is not necessary at all, just to familiarize yourself with the wrap method]

Here we will copy the new extend method when calling obj_1.extend (obj_2, true.

Because extend is our custom, it will be enumerated by the in operation. The second problem below is related to this custom attribute.

Another problem is the implementation of in operations in some ie6.

In the following cases, if we re-write an attribute that is not enumerated in a prototype similar to tostring () in a source object, under normal circumstances, the in operator can be used to obtain the rewritten tostring (just like the extend we added in the previous example). However, IE6 continues to block the tostring in this case, so this value cannot be obtained.
See the following example:

    (function(){
return;
var obj_1 = {
name : 'xesam'
};
var obj_2 = {
age : '24',
toString:function(){return ('my toString');}
};
function extend(destination, source) {
for (var property in source){
destination[property] = source[property];
}
return destination;
}
extend(obj_1,obj_2);
alert(obj_1.toString());
})();

Normally, the "My tostring" dialog box is displayed. However, in IE6, The tostring method of the original object is called because obj_1 does not get this rewrite, therefore, the pop-up dialog box is "Object object ".

Therefore, if you want to be more general, you have to check the compatibility issue in advance. A reference code:

(Function (){
VaR dontenum = (function () {// (1) first checks whether custom attributes are blocked.
VaR o = {tostring :''}
For (var I in O ){
Return true;
}
Return false;
})();
VaR dontenumarray = ['tostring', 'valueof ']; // (2) the array is supplemented.

VaR obj_1 = {
Name: 'xesam'
};
VaR obj_2 = {
Age: '24 ',
Tostring: function () {return ('My tostring ');}
};

Function extend (destination, source ){
If (! Dontenum ){
For (var j = 0, Len = dontenumarray. length; j <Len; j ++ ){
If (source. hasownproperty (dontenumarray [J]) {
Destination [dontenumarray [J] = source [dontenumarray [J];
}
}
}
For (VAR property in source ){
Destination [property] = source [property];
}
Return destination;
}
Extend (obj_1, obj_2 );
Alert (obj_1.tostring ());
})();

[Note (1) (2): This code is not complete, because you have to determine which attributes are blocked by IE6 or other browsers and you need to test them one by one]

 

Let's talk about this in the static method of object. There are other things. We will continue tomorrow...

 

For more information, see http://www.cnblogs.com/xesam /]
Address: http://www.cnblogs.com/xesam/archive/2011/12/21/2295336.html

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.