纸上得来终觉浅,绝知此事要躬行。

 

JavaScript中call和apply的区别

<html>
    <head>
        <title><T></title>
        <script type="text/javascript">
            var User = function (name) {
                this.Name = name;
                console.log(this);
            }
            
            var BaseInfo = function(){
                this.Age = arguments.length > 0 ? arguments[0] : 1;
            }
            
            var u = new User("H");
            //BaseInfo.call(u);
            // 或 : 
            //BaseInfo.apply(u,[23,56]);
            
            //console.log(u.Name);
            //console.log(u.Age);
            
            // bind 方法
            Function.prototype.bind = function(obj) {
                var method = this,
                
                temp = function() {
                    return method.apply(obj, arguments);
                };
                
                return temp;
            }
            
            var obj = BaseInfo.bind(u);
            obj(24);
            console.log(u.Name);
            console.log(u.Age);
        </script>
    </head>
    
    <body>
        
    </body>
</html>

 

posted on 2013-08-26 10:52  JRoger  阅读(201)  评论(0)    收藏  举报

导航