普通对象和函数对象
Javascript
是面向对象的编程,所以所有的一切都是对象,但是对象和对象之间也是有区别的。在JavaScript
中主要是普通对象和函数对象。其中通过new Function()
创建的都是函数对象。
function f1(){}
var f2 = function(){}
var f3 = new Function('',函数体);
上面的方法都是本质上都是通过new Function()
来进行实例化的,但是其他的对象一般我们都默认是普通的对象。
构造函数
上一段代码:
function Student (name,age,sex){
this.name = name;
this.age = age;
this.sex = sex;
}
var student1 = new Student('kim',15,'female');
var student2 = new Student('zgl',1,'female');
现在student1
、student2
都是Student
的实例,而且这两个实例都有constructor
的属性,这个属性在本质上是一个指针,指向了构造了这个实例的原型,在这里的体现就是student1
的constructor
指向了Student
。一句话总结:实例的构造函数属性constructor
指向构造函数。
console.log(student1.constructor === Student) //true
prototype和_proto_
因为JavaScript是面向对象的编程,在这里提出一个概念:“一切都是对象”,所以当我们定义一个对象的时候,会先预定义一些属性。在这里就要说一下prototype
和__proto__
的概念,只有函数对象会有prototype
这个属性,而且这个属性都是指向函数的原型对象的。对于普通对象仅仅拥有__proto__
,原型对象究其本质,就是一个对象,但是这个对象,是默认生成的,但是我们可以通过一定的操作对原型对象进行赋值和扩展.。
先来一段代码的演示:
Student.prototype ={
name : 'kimm',
sayname: function(){
console.log(this.name);
}
constructor: Student
}
简单的来说,每一个原型对象都会自动的获取一个constructor
属性,正如上面说的constructor
是一个指针。这个指针指向prototype
所在的函数。
Student.prototype.constructor == Student //true
我们现在总结一下,我们已经做了哪些相等的操作:
student1.constructor == Student
Student.prototype.constructor == Student
但是从本质上面看,student1和student2并没有constructor
属性,constructor
这个属性是是属于 prototype
的原型对象的,从概念上面来说student1和student2这两个实例其实和构造函数是没有什么直接的关系的,student1、student2和Person的原型对象才有直接的关系