JavaScript 函数和对象

在javascirpt 世界中,所有的函数都是对象,并且还可以被用来创建对象。

function make_person(firstname, lastname, age) {
    person = {};
    person.firstname = firstname;
    person.lastname = lastname;
    person.age = age;
    return person;
}
make_person("Joe", "Smith", 23);
// {firstname: "Joe", lastname: "Smith", age: 23}
但是,为了能够创建一个特定类型的对象(也就是能继承原型,拥有一个构造器的那种), 函数能获取this引用而且如果这个函数式通过new关键字,这个函数会返回一个包含了所有的定义在this上的属性的对象。 在这种情况下, this引用指向的是这个我们新创建的对象。

function make_person_object(firstname, lastname, age) {
    this.firstname = firstname;
    this.lastname = lastname;
    this.age = age;
    // 注意,我们并没有return语句。
}
make_person 和 make_person_object 两者最关键的不同是:

1. 对于make_person,无论我们是去通过new关键字去调用 make_person() 还是直接简单的调用make_person(), 这两者没有任何区别, 两个都会产生同样的对象。

2. 但是对于make_person_object, 如果我们不是通过new关键字去调用的,this将指向的是不确定的对象,如果make_person_object,是个全局函数,那this一般指向的是window对象, 那我们在this上定义的firstname, lastname, age属性,其实是赋给了window对象。

var Joe = make_person_object("Joe", "Smith", 23);
console.log(Joe); // undefined
console.log(window.firstname) // "Joe" (oops)

var John = new make_person_object("John", "Smith", 45);
console.log(John); // {firstname: "John", lastname: "Smith", age: 45}

正如我上面说的,通过make_person_object方式去创建对象,能让我们事后对person对象增加方法和属性

make_person_object.prototype.full_name = "N/A";
make_person_object.prototype.greet = function(){ 
    console.log("Hello! I'm", this.full_name, "Call me", this.firstname); 
};
John.full_name // "N/A"
John.full_name = "John Smith"; 
make_person_object.full_name // Still "N/A"
John.greet(); // "Hello! I'm John Smith Call me John"

当然,还要注意,传统意义上讲,构造器类型的函数名称如:make_person_object应该是大写的,单个单词,是个名词,所有我们应该定义一个Person构造器而不是make_person_object.

原文地址:https://www.cnblogs.com/peteryan/p/3791811.html