JavaScript在构造函数之外创建对象并添加2个方法

时间:2019-06-15 12:30:41

标签: javascript methods constructor

我有一个构造函数Example,它具有2个方法。

我想在构造函数之外创建一个新对象,并调用其中的2个方法。

我该怎么做,任务没有说明其余内容。

类似于var newEx = new Example的对象将创建一个与构造函数相同的对象。

谢谢

function Example (){
    this.name = Mike;
    this.surname = Ryan;
    this.age = 50;
    this.x = function(){
        return 20
    }
    this.y = function (){
        return 50
    }
}

1 个答案:

答案 0 :(得分:0)

适合您的简单示例
我认为它将帮助您理解。

function Person(name,dob){
    this.name = name;
    this.birthday = new Date(dob);
    this.calAge = function(){
        const diff = Date.now() - this.birthday.getTime();
        const ageDate = new Date(diff);
        return Math.abs(ageDate.getUTCFullYear() - 1970 );
    }
}

const shovon = new Person('Shovon', '8-26-1991');
console.log(shovon);
console.log(shovon.name);
console.log(shovon.calAge());

现在,通过您的代码

function Example(){
    this.name = Mike;
    this.surname = Ryan;
    this.age = 50;
    this.x = function(){
        return 20
    }
    this.y = function (){
        return 50
    }
}

const newObj = new Example(); // New Object Created
newObj.x(); // call x function , it will execute and return 20
console.log(newObj.x()); // Now it will show the result in console

//You can store the return value in a variable like this 
var a = newObj.x();