Javascript小结

http://bonsaiden.github.com/JavaScript-Garden/zh/#function.closures

Variable Declarations are Hoisted



var myvar = 'my value';  
  
(function() {  
  alert(myvar); // my value  
})();  

All right, all right. Still obvious, I know. Now, let’s throw a wrench into the mix, and create a local variable within this anonymous function of the same name.

  var myvar = 'my value';  
  
(function() {  
  alert(myvar); // undefined  
  var myvar = 'local value';  
})();  

Javascipt Inheritance

The following are some useful functions definition from “Javascript – the good part”. Just make a note.

Function.prototype.method = function (name, func) {
                this.prototype[name] = func;
                return this;
}
Function.method(‘inherits’, function(parent){
                this.prototype = new parent();
                return this;
})
 
function Parenizor(value) {
                this.setValue(value);
}
Parenizor.method(‘setValue’, function(value){
                this.value = value;
                return this;
});
Parenizor.method(‘getValue’, function(value){
                return this.value;
})
Object.method(‘superior’, function(name){
                var that = this,
                        method = that[name];
                return function () {
                return method.apply(that, arguments);
}
})
 
function ZParenizor(value) {
                this.setValue(value);
}
ZParenizor.inherits(Parenizor);

Prototype inheritance

 

If (typeof Object.create !== ‘function’) {
                Object.create = function (o) {
                                function F() {}
                                F.prototype = o;
                                return new F();      
                 };
}
newObject = Object.create(oldObject);
 
Array.method(‘reduce’, function(f, value){
                var    i;
                for ( i = 0; i < this.length; i += 1){
                value = f(this[i], value);
}
return   value;
});
var is_array = function(value){
                return value &&
                                typeof value === ‘object’ &&
                                value.constructor === Array;
};

http://msdn.microsoft.com/en-us/magazine/ff852808.aspx

About Prototype.

Every object in JavaScript holds a hidden piece of state – a reference to another object known as the object’s prototype. The array we created earlier references a prototype object, and so does the point object we created. I say the prototype reference is a hidden, but there are implementations of ECMAScript (JavaScript’s formal name) that allow us to grab this prototype reference using an object’s __proto__ property (Google Chrome, for example.

Sharing Prototype.

The true magic of prototypes in JavaScript is how multiple objects can maintain references to the same prototype object. For example, if we create two arrays:

1.        var myArray = [12];
2.        var yourArray = [456];

Then both arrays will share the same prototype object, and following code evaluates to true:

1.        Object.getPrototypeOf(myArray) === Object.getPrototypeOf(yourArray);

Of Functions

Every function object in JavaScript has a prototype property. Do not confuse this prototype property with the __proto__ property  – they do not serve the same purpose or point to the same object.

1.        // this returns true
2.        Object.getPrototypeOf(Array) != Array.prototype

Array.__proto__ gives us the prototype for Array – think of this as the object the Array function inherits from.

Array.protoype, on the other hand, is the prototype object for all arrays. That is, it’s the prototype object for array objects like myArray, and it contains the methods all arrays will inherit. We can write some code to prove this fact.

1.        // true
2.        Array.prototype == Object.getPrototypeOf(myArray)
3.         
4.        // also true
5.        Array.prototype == Object.getPrototypeOf(yourArray);

We can also redraw our previous diagram with this new knowledge

Constructor Functions

A constructor function is just a regular JavaScript function object with two distinguishing characteristics.

1.        The first letter of a constructor function is capitalized by convention (making it easy to identify constructor functions).

2.        A constructor function expects to be used in conjunction with the new operator to construct objects.

Array is one example of a constructor function. The Array function expects you to use it with a new operator, and its first letter is a capital letter. JavaScript includes the Array function as a built in object, but anyone can author a constructor function.

1.        var Point = function (x, y) {
2.            this.x = x;
3.            this.y = y;
4.            this.add = function (otherPoint) {
5.                this.x += otherPoint.x;
6.                this.y += otherPoint.y;
7.            }
8.        }
9.         
10.     var p1 = new Point(34);
11.     var p2 = new Point(86);
12.     p1.add(p2);

The problem now is we still have an add method inside of each point. Applying what we know about prototypes and inheritance, we’d prefer to have the add method in Point.prototype instead of each point. To achieve inheritance of the add method, all we need to do is modify the Point.prototype object.

1.        var Point = function (x, y) {
2.            this.x = x;
3.            this.y = y;
4.        }
5.         
6.        Point.prototype.add = function (otherPoint) {
7.            this.x += otherPoint.x;
8.            this.y += otherPoint.y;
9.        }
10.      
11.     var p1 = new Point(34);
12.     var p2 = new Point(86);
13.     p1.add(p2);

 

About new operator

 

var o = new Array();

The new operator in JavaScript has three essential tasks. First, it creates a new empty object. Next, it sets the new object’s __proto__ property to match the prototype property of the function being invoked. Finally, the operator invokes the function and passes the new object as the “this” reference. If we were to expand out those last two lines of code, the script would look like this.

var o = {};
o.__proto__ = Array.prototype;
Array.call(o);

 

http://stackoverflow.com/questions/383402/is-javascript-s-new-keyword-considered-harmful

Use of the functionality provided by the new keyword has several advantages over building each object from scratch:

1.     Prototype inheritance. While often looked at with a mix of suspicion and derision by those accustom to class-based OO languages, JavaScript's native inheritance technique is a simple and surprisingly effective means of code re-use. And the new keyword is the canonical (and only available cross-platform) means of using it.

2.     Performance. This is a side-effect of #1: if I want to add 10 methods to every object I create, I couldjust write a creation function that manually assigns each method to each new object... Or, I could assign them to the creation function's prototype and use new to stamp out new objects. Not only is this faster (no code needed for each and every method on the prototype), it avoids ballooning each object with separate properties for each method. On slower machines (or especially, slower JS interpreters) when many objects being created this can mean a significant savings in time and memory.

And yes, new has one crucial disadvantage, ably described by other answers: if you forget to use it, your code will break without warning. Fortunately, that disadvantage is easily mitigated - simply add a bit of code to the function itself:

function foo()
{
   // if user accidentally omits the new keyword, this will 
   // silently correct the problem...
   if(!(thisinstanceof foo))
      returnnew foo();

   // constructor logic follows...
}

Now you can have the advantages of new without having to worry about problems caused by accidentally misuse. You could even add an assertion to the check if the thought of broken code silently working bothers you. Or, as some commented, use the check to introduce a runtime exception:

if(!(thisinstanceof arguments.callee))
   thrownewError("Constructor called as a function");

(Note that this snippet is able to avoid hard-coding the constructor function name, as unlike the previous example it has no need to actually instantiate the object - therefore, it can be copied into each target function without modification.)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值