关于JavaScript原型继承的小小疑惑 财富值75

2016-10-30 10:59发布

//定义一个book对象 var Book = function(title, publisher) {     this.title = title;     this.publisher = publisher; }; //于是在原型对象中增加一个sayTitle()方法,用来显示书名 Book.prototype.sayTitle = function() {     alert(this.title); }; //实例化对象 var book1 = new Book("High Performance JavaScript", "Yahoo Press"); //输出"High Performance JavaScript" book1.sayTitle();  //又定义了一个对象 var people = function(age,name,title){   this.age = age;   this.name = name;   this.title = title; }; var p = new people(25,"William","Programmer");    //实例化 p.sayTitle();  //报错:Uncaught TypeError: p.sayTitle is not a function

疑惑:book的原型指向的是Object,通过prototype新加的sayTitle()方法应该是加到Object对象上啊,为什么新的people对象不能用sayTitle()方法?

友情提示: 此问题已得到解决,问题已经关闭,关闭后问题禁止继续编辑,回答。
3条回答

你再运行这段代码看看结果。

一周热门 更多>