是否可以在JS中不创建对象的情况下调用构造函数方法?

时间:2017-03-12 09:56:35

标签: javascript constructor

我不确定object literal和构造函数之间的区别。

function user() {
    this.name="john"
    this.getName=function (){
        return this.name;
    };
}

var johnUser=new user();
console.log(johnUser.getName()); // Will console john

如果我想在不创建Java静态方法/函数之类的任何对象的情况下调用getName该怎么办?

如果我可以添加

user.sayName=function() {
    console.log("Hey there");
}

console.log(user.sayName()); //will console Hey there.

如何访问构造函数属性?

3 个答案:

答案 0 :(得分:3)

答案是你不能。 您应该已经阅读过JS中函数的上下文如何工作。

当您使用 new 运算符时,空对象作为上下文传递,这就是为什么您可以指定 this 的属性(这是对函数上下文的引用)

当您在没有 new 运算符的情况下调用函数时,您的函数的上下文是eiter全局对象(窗口)或未定义。您可以在函数中打印 this ,以查看您拥有ATM的上下文。

您(可能)想要的是创建prototype

答案 1 :(得分:0)

对象文字

var user = {
    name: "John",
    getName: function(){
        return this.name;
   }
};

或者,此方法不会定义对象。

function sayName()
{
    return "just a string";
}

答案 2 :(得分:0)

function user() {
    this.name = 'john';
}

user.prototype.getName = function(){ return this.name; }

var johnUser = new user();

console.log( johnUser.getName() )       // john
console.log( user.prototype.getName()); // undefined

user.prototype.getName = function(){ return 'just a string' }

console.log( johnUser.getName() )      // just a string
console.log( user.prototype.getName());// just a string

user.prototype.getName = function(){ return this.name || 'just a string'; }

console.log( johnUser.getName() )      // john
console.log( user.prototype.getName());// just a string
相关问题