您的位置:首页 > Web前端 > JavaScript

理解js原型和原型链

2016-01-18 19:56 786 查看
一. 普通对象和函数对象:

js中,万物皆对象,大体分为两种:普通对象,函数对象。凡是通过new Function()创建的都是函数对象,其他的则为普通对象。

下面举例说明:

function fun1(){}; //function
var fun2 = function(){}; //function
var fun3  = new Function("formalParameter","console.log(formalParameter);"); //function

var object1 = new fun1(); //object
var object2 = { }; //object
var object3 = new Object(); //object


二. 原型对象

在js中,每定义一个对象(函数)时,对象中都包含一些预定义的属性,其中函数对象的一个属性就是原型对象”prototype”。普通对象没有prototype属性,但是有 “proto“属性。

原型对象其实就是普通对象,但是Function.prototype除外,他是函数对象,并且没有prototype属性。

function foo(){};
console.log(typeof(foo)); //function
console.log(typeof(foo.prototype)); //object
console.log(typeof(Function.prototype)); //function
console.log(typeof(Object.prototype)); //object
console.log(typeof(Function.prototype.prototype)); //undefined


foo.prototype是foo的一个实例化对象,当创建foo时,同时创建了foo的实例化对象并且赋值给foo的prototype,基本过程如下:

var temp = new foo();
foo.prototype = temp;


所以,Function.prototype为什么是函数对象就明了了。

var temp = new Function();
Function.prototype = temp;


原型对象的主要用途:继承。

function Parent(username){
this.username = username;
}
Parent.prototype.hello = function(){
console.log("hello, I am "+this.username);
}
function Child(username,password){
this.username = username;//必须初始化
this.password = password;
}
Child.prototype = new Parent();
Child.prototype.pass = function(){
console.log(this.password);
}
//测试
var parent = new Parent("zhangsan");
var child = new Child("lisi","123456");
parent.hello();
child.hello();
child.pass();
console.log(child instanceof(Parent));


三. 原型链

js在创建(普通/函数)对象时,都有一个”proto“内置对象,用于指向创建他的函数对象的原型对象prototype。

console.log(parent.__prpto__ === Parent.prototype); //true
console.log(Parent.prototype.__proto__ === Object.prototype)//true
console.log(Object.prototype.__proto__) //null


四.内存构造

var person = function(name){
this.name = name
};
person.prototype.getName = function(){
return this.name;
}
var zjh = new person(‘zjh’);
zjh.getName(); //zjh




五.constructor

原型对象prototype中都有预定义的constructor属性,用来引用他的函数对象。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: