//定义一个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()方法?
类的原型和
Object
到底啥关系?一周热门 更多>