//定义声明这样一个类
function User() {
            this.name = "LiXin";
            this.say = function () {
                alert(this.name);
            }
        }
然后进行实例化
var test=new User().say();
实例化的时候,在say函数里面的this为什么不是指向的say,而是指向的User呢?
say也是一个function,new的时候为什么是new User,而不是new say?

解决方案 »

  1.   

    在这里say()方法相当于User的一个变量,只是这个变量是方法的形式。
    为什么是new User,而不是new say?,你见过new变量的吗?,嘿嘿,这是个人理解,希望对你有帮助。
      

  2.   

    会不会是在new User的时候,this.say就这句已经把say作为User的方法了,所以这个方法里的this也是指的User,不过就是不知道我这样理解是不是对的
      

  3.   

    实例化后就是一个对象了  this总是指向调用它的对象
      

  4.   

    当你new一个对象的时候
    function User() {
                this.name = "LiXin";//这个this就是那个new 的对象,
                this.say = function () {//用这个对象调用方法,方法里面的this就是外面调用他的对象
                    alert(this.name);
                }
            }
    当你不new对象时,直接User()调用的话
    function User() {
                this.name = "LiXin";//这个this一般就是window
                this.say = function () {//用这个对象调用方法,方法里面的this就是外面调用他的对象
                    alert(this.name);
                }
            }
    因为这个function User() {类,他是定义在window下的,所以可以理解为window.User();这样的调用.
    并不一定User();调用里面的this就是this,那要看实际的运行环境了。
      

  5.   

    当一个function被当做一个对象的方法调用的时候, this就指向这个对象。推荐你看 Javascript 语言精粹这本书,很薄的一本。
      

  6.   


    /*了解了new的基本原理就明白了.*/
    <script type="text/javascript">
    // instance --> new 模拟
    var instance = function(source) {
    var p = {};
    var args = Array.prototype.slice.call(arguments, 1);
    source.apply(p, args); // 这里p通过apply借用了User的指针
    p.__proto__ = source.prototype;
    return p;
    }function User() {
    this.name = "LiXin";
    this.say = function() {
    alert(this.name);
    }
    }var test = instance(User).say();
    </script>
      

  7.   


    instance就是new实现的原理.注释的那句apply知道啥意思.就应该明白了this为啥指向User[source参数就是User]
      

  8.   


    补充: 以上模拟代码在firefox下运行
      

  9.   

    我晕. 都写成那样 还看不懂 就补基础吧 apply都不会 那怎么讲?
      

  10.   

    this代表调用当前运行的对象
    new User().say();
    new User  代表一个对象
    . 代表了调用
    say() 代表了一运行
      

  11.   

    在new User的时候,this.say就这句表示对say变量的初始化,this当然指的是User啦。