首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > JavaScript >

js原型的有关问题,很奇怪

2013-03-28 
js原型的问题,很奇怪User.prototype.sayHellofunction(){alert(hello)}user.sayHello()这样的话弹出h

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();

热点排行