使用构造函数时,我们在构造函数中定义了属性和方法 所以为什么我必须将方法附加到原型上 这有什么重要性? 像这个例子:
// using constructor
function User(email,name){
this.email = email ;
this.name = name ;
this.online = false ;
this.login = function(){
console.log(this.email,'has logged in') ;
}
}
var userOne = new User('john@gmail.com', 'john');
var userTwo = new User('sam@gmail.com' , 'sam ');
console.log(userOne.login()) ;
// using prototype
function User(email,name){
this.email = email ;
this.name = name ;
this.online = false ;
}
User.prototype .login = function(){
console.log(this.email,'has logged in') ;
}
var userOne = new User('john@gmail.com', 'john');
var userTwo = new User('sam@gmail.com' , 'sam' );
console.log(userOne.login());
带有和不带有原型的代码的输出相同: john@gmail.com已登录