美文网首页
深入理解 Function constructor - java

深入理解 Function constructor - java

作者: Zihowe | 来源:发表于2017-08-28 04:00 被阅读6次

使用new关键字发生了什么
使用new 关键字就是新创建一个对象。

调用这个方程发生了什么
调用方程之后,就会执行方程里的代码块。
我们知道,方程也是对象,可以绑定属性,方法。
在这里就是绑定了属性。

方程的this为什么指向新的对象
调用方程时,会有一个新的执行环境创建。
this本俩应该是外面的全局this,但是非常重要的一点是new创建了一个新的对象给这个方程,所以这个方程的this指向了这个新的对象。

整个过程
整个过程就是,new创建新的对象,call function来绑定属性到这个新的对象,最后会自动function返回这个对象,如果我们没有设置这个func返回值的话。

Function constructor:
A normal function that is used to construct objects.
The 'this' variable points a new empty object, and that object is returned from the function automatically.

.prototype

我们如何绑定method

每个方程都会有一个prototype属性,这个属性一开始是个empty object。(注意这个prototype不是这个__prototype__。)

当我们不使用functioncontructor职能时,这个prototype没有任何用处。

但当我们使用function做为构造函数时,这个prototype就是所有新的object__prototype__了。如下图:

image.png

如果我们直接在构造函数里面加入method的话,因为方程也是一个对象,所以如果创建了一千个对象使用new关键字,那么每个对象都会复制这个method,空间浪费。

为了避免浪费,我们使用prototype来绑定method,这样就只有一份方程。

每个新的对象的原始类型prototype就是Person,使用John.prototype会得到Person{}

当我们想使用method时,如果当前对象没有这个方法,就会自动向上搜索这个方法,而Person对象里面有,就会调用它。即使我们已经创建了1000个新的对象,给Personprototype添加方法,这1000个对象也可以使用。

这样,我们知道,在方程里面添加属性给每个object,在prototype添加方法。

image.png
function Person(firstname, lastname) {
 
    console.log(this);
    this.firstname = firstname;
    this.lastname = lastname;
    console.log('This function is invoked.');
    
}

Person.prototype.getFullName = function() {
    return this.firstname + ' ' + this.lastname;   
}

var john = new Person('John', 'Doe');
console.log(john);

var jane = new Person('Jane', 'Doe');
console.log(jane);

Person.prototype.getFormalFullName = function() {
    return this.lastname + ', ' + this.firstname;   
}

console.log(john.getFormalFullName());

built-in function constructor

String.prototype.isLengthGreaterThan = function(limit) {
    return this.length > limit;  
}

console.log("John".isLengthGreaterThan(3));    // javascript会自动将一个string boxing为一个object

Number.prototype.isPositive = function() {
    return this > 0;   
}

相关文章

网友评论

      本文标题:深入理解 Function constructor - java

      本文链接:https://www.haomeiwen.com/subject/krkwdxtx.html