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.
- 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.
- Regional and general constructor function is invoked in different ways. Normal function is called directly, the constructor calls need to use the new keyword.
- 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
- 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.
- 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
- 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.