简体   繁体   English

javascript新的对象构造函数替代正确吗?

[英]javascript new object constructor function alternative proper?

Okay, so I've been reading https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new And find myself writing a bunch of object construction code in a class sort of scheme. 好的,所以我一直在阅读https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new并发现自己以类计划的方式编写了一堆对象构造代码。

To maintain backward compatibility I haven't been using 'class' keyword/syntax much. 为了保持向后兼容性,我没有过多使用'class'关键字/语法。

You may have seen this before: 您可能之前已经看过:

function Car(make, model, year) {
    this.make = make;
    this.model = model;
    this.year = year;
}
//Usage: var carinstance = new Car("blah","blah","blah");

But I've found that this works quite well for my use (found by accident): 但是我发现这很适合我使用(偶然发现):

function Player (name) {
    var p = {
        name : name,
        age : 18
    };
    return p;
}
//Usage: var person = new Player("Jon");

I know it works , as I've used it. 我知道它有效 ,因为我已经使用过。 I just don't know if this is proper. 我只是不知道这是否合适。

For example, I can use the same code w/o 'new' keyword (same result): 例如,我可以使用不带“ new”关键字的相同代码(结果相同):

var person = Player("Jon");

But I cannot do the same with the first specification (using 'this' keyword in a function): 但是我不能对第一个规范做同样的事情(在函数中使用'this'关键字):

var car = Car("blah","blah","blah"); //car == undefined

I don't really know how to google this, or what to call it. 我真的不知道怎么用谷歌搜索,或称它为什么。 I was hard enough trying to figure out what title this question should have. 我很努力地试图弄清楚这个问题应该有什么标题。

I guess a more definitive way to put the question: Are the results I'm getting just a quark of javascript, browser engine, etc? 我猜想可以用一种更为明确的方式来提出这个问题:我得到的结果只是一堆JavaScript,浏览器引擎等? Or is this a solid way to make a constructor function? 还是这是构造函数的可靠方法?

Do the following. 请执行下列操作。

function Car(make, model, year) {
    if ( !(this instanceof Car) )
      return new Car(make, model, year);
    this.make = make;
    this.model = model;
    this.year = year;
}

and then you can call it without new. 然后您就可以不加任何新意地调用它。

Because in Player function, it returns p object. 因为在Player函数中,它返回p对象。 So, if you use new operator call Player function, it will be p object but not the default created obj.Of course, it will also return p object when you call Player in general. 因此,如果您使用new运算符调用Player函数,它将是p对象,而不是默认创建的obj。当然,通常在您调用Player时也会返回p对象。 However, in Car function, it doesn't return an object.Therefore, when you use new operator call Car function, it will return the default created an object and it will return undefined with calling Car function in general. 但是,在Car函数中,它不会返回对象,因此,当您使用new运算符调用Car函数时,它将返回默认创建的对象,并且通常会通过调用Car函数返回undefined的对象。

you can refer: 您可以参考:

usage of new operator 新操作符的用法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM