日期:2014-05-16  浏览次数:20316 次

js原型的问题,很奇怪
User.prototype.sayHello=function(){
alert("hello");
}
user.sayHello();
这样的话弹出hello
但是我换一种方式
var user=new User();User.prototype={
sayHello:function(){
alert("hello");
}
}user.sayHello();
ff报user.sayHello is not a function
javascript prototype js原型

------解决方案--------------------
User.prototype={};
原型的绑定不能晚于对象的创建,也就是说要在new对象前。
User.prototype.sayHello = function(){}
给原型添加一个方法后,该构造函数的实例都会有。
------解决方案--------------------

function User(){
//code here
}

假设此时User的原型(User.prototype)是User_proto。那么当
var user=new User()

user的原型是User_proto。
此时

User.prototype.sayHello=function(){
            alert("hello");
}

只是在User_proto上添加了一个sayHello方法。user.sayHello可用。
但是,当

User.prototype={
      sayHello:function(){
            alert("hello");
      }
}

把User类的原型换成。可是user的原型并没有换。还是老的User_proto。所以user.sayHello不可用
------解决方案--------------------
function User(){
            //code here
        }
        var methods={
            sayHello:function(){
                alert("hello");
            }
        }
        
        methods={
            sayHello:function(){
                alert("hello");
            },
            sayWord:function(){
                alert("word");
            }
        }
        User.prototype=methods;
        var user=new User();
        user.sayWord();