Create objects using factory methods and constructors

1. Create an object using the factory method: large quantities of objects created by this method.

function createPerson(name) {
	// 创建一个新对象
	var obj = new Object();
	// 向对象中添加属性
	obj.name = name
	obj.sayname = function() {
		alert(this.name);
	}
	// 返回新对象
	return obj;
}

var obj2 = createPerson("孙悟空");
console.log(obj2);

Limitations: Use an object factory method created using the constructor are the object, so the object you create is object of this type, we're unable to distinguish between a variety of different types of objects.

2. Use the constructor, created specifically Person object.

  1. The constructor is an ordinary function, create mode and normal function is no different. The difference is that the constructor's first letter capitalized habit.
  2. Regional and general constructor function is invoked in different ways. Normal function is called directly, the constructor calls need to use the new keyword.
  3. Constructors execution process:
    (1) create a new object immediately.
    (2) the new object as a function of this, in this function may be used to refer to the new object.
    (3) line by line function code.
    (4) New Object returned as a return value.
function Person(name) {
	this.name = name
	this.sayName = function() {
		alert(this.name)
	}
}
function Dog(name) {
	
}
var per = new Person(name);
var dog= new Dog();
console.log(per)  
console.log(dog)

After executing the above code type Person, Dog

  1. Use objects created with a constructor, we called a class of objects, also known as a constructor of a class. We will create an object constructor, called an instance of that class. Person class, Dog class.
  2. Use instanceof can check whether an object is an instance of a class. Syntax: instanceof Object constructor, if it is true otherwise it is false.
console.log(per instanceof Person) // true
  1. All objects are descendants of Object, so any object and Object and returns instanceof checks are true.
console.log(per instanceof Object) // true

this:
When you call a function in the form of, this is the window.
When the form of method invocation, who call the method this is who.
When in the form of a constructor call, this is the newly created object.

Published 27 original articles · won praise 4 · Views 2825

Guess you like

Origin blog.csdn.net/qq_39083496/article/details/102768550