如何在不使用关键字的情况下使用面向对象(' new')

时间:2016-03-13 17:06:07

标签: javascript oop

我想做的是如下:

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

// This will return error;
console.log(Person('John').getName());
// While this won't.
var p1 = new Person('john');
console.log(p1.getName());

我误解了什么吗?

5 个答案:

答案 0 :(得分:2)

// This will return error;
console.log(Person('John').getName());

它返回错误bcoz Person()默认返回undefined,但是如果你使用new它将返回新创建的对象。

// While this won't.
var p1 = new Person('john');
console.log(p1.getName());

这样可以返回一个设置为__proto__ Person.prototype的新对象,并且因为它上面有一个getName(),它会按预期工作。

您可以使用范围安全构造函数使构造函数在没有显式new的情况下工作。

function Person(name) {
  if(this instanceof Person) {
    this.name = name;
  } else {
    return new Person(name);
  }
}

http://www.mikepackdev.com/blog_posts/9-new-scope-safe-constructors-in-oo-javascript

答案 1 :(得分:0)

如果您不想使用new关键字,可以使用Object.create()。以下是MDN的一个例子:

// Animal properties and method encapsulation
var Animal = {
  type: "Invertebrates", // Default value of properties
  displayType : function(){  // Method which will display type of Animal
    console.log(this.type);
  }
}

// Create new animal type called animal1 
var animal1 = Object.create(Animal);
animal1.displayType(); // Output:Invertebrates

// Create new animal type called Fishes
var fish = Object.create(Animal);
fish.type = "Fishes";
fish.displayType(); // Output:Fishes

答案 2 :(得分:0)

如果您不想在代码中使用new关键字(而且我想不出有这么好的理由,那么您基本上会隐藏重要信息),您可以做类似的事情:

var pPerson = function(name) {
   this.name = name;
};

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

var Person = function (name) {
    return new pPerson(name);
};

答案 3 :(得分:0)

如果你真的非常讨厌自己,你可以这样做

var Person = function(name) {
   var This = {}; 

   This.name = name;

   //See note
   Object.setPrototypeOf(This, arguments.callee.prototype);  

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

var p = Person('John');
console.log(p.getName());

注意 你绝对必须阅读this

答案 4 :(得分:0)

您可以尝试将原型函数创建为父函数本身的一部分。



var Person = function(name) {
  this.name = name;
  this.get_name = function() {
    return this.name;
  }
  return this;
}

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

// This will return error;
console.log(Person('John').get_name());

// While this won't.
var p1 = new Person('john');
console.log(p1.getName());