js的原型prototype究竟是什么?

Javascript也是面向对象的语言,但它是一种基于原型Prototype的语言,而不是基于类的语言。在Javascript中,类和对象看起来没有太多的区别。

1.什么是prototype:

function定义的对象有一个prototype属性,prototype属性又指向了一个prototype对象。在prototype对象中有一个constructor属性,这个constructor属性同样指向一个constructor对象,而这个constructor对象恰恰就是这个function函数本身。 用伪代码和图表表示如下:

 

 

 

可以看出这里的prototype是链状的。employee.prototype对象中的constructor属性指向employee函数。

源码:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
</head>
<body>

<script>
function employee(name,jobtitle,born){
    this.name=name;
    this.jobtitle=jobtitle;
    this.born=born;
    this.test = function(){
    console.log("test...");}
}
var fred=new employee("Fred Flintstone","Caveman",1970);
employee.prototype.salary=null;
fred.salary=20000;
document.write(fred.salary);
</script>

</body>
</html>

 

2.prototype的作用:

    prototype允许我们在创建对象之后来改变对象或类的行为,并且这些通过prototype属性添加的字段或方法所有对象实例是共享的。

posted @ 2017-10-22 20:08  董永辉Bruno  阅读(7593)  评论(0编辑  收藏  举报