将方法直接附加到构造函数并将其附加到原型之间有什么区别

时间:2019-05-05 11:50:04

标签: javascript object

使用构造函数时,我们在构造函数中定义了属性和方法 所以为什么我必须将方法附加到原型上 这有什么重要性? 像这个例子:

// 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已登录

0 个答案:

没有答案