原型中原来的study()方法没有了 Student.prototype = new Person(); var stu
1.原型的引入
代码一
function Person(name, age){ this.name = name; this.age = age; this.eat = function() { console.log("eat..."); }; } var per1 = new Person("小白", 10); var per2 = new Person("小黑", 10); console.log(per1.eat == per2.eat);//false
如何实现函数共享, 代码二:
function myEat(){ console.log("今天吃红烧土豆"); }; function Person(name, age){ this.name = name; this.age = age; this.eat = myEat; } var per1 = new Person("小白", 10); var per2 = new Person("小黑", 10); console.log(per1.eat == per2.eat);//true
但是代码二欠好,因为外面可能界说变量var myEat = 10;造成定名斗嘴。
2.原型添加要领解决数据共享
代码:
function Person(name, age){ this.name = name; this.age = age; } //通过原型来添加要领 Person.prototype.eat = function() { console.log("eat..."); }; var per1 = new Person("zs1", 10); var per2 = new Person("zs2", 20); console.log(per1.eat == per2.eat);//true console.dir(per1); //通过浏览器检察,发明实例东西中没有eat()要领 console.dir(per2); console.dir(Person);
之前的写法
Student.prototype.height=""; Student.prototype.weight=""; Student.prototype.study=function(){}; Student.prototype.eat=function(){};
* 简单的原型语法
Student.prototype={ constructor:Student, height:"", weight:"", study:function(){}, eat:function(){} };
3.实例东西使用的属性和要领层层的搜索
实例东西使用的属性或要领,,先在实例中查找,找到了直接使用,找不到,去对应的结构函数的原型东西prototype中查找,找不到,则报错。
4.为内置东西的原型东西中添加要领
我们能否为系统的内置东西的原型中添加要领(相当于转变源码)? 可以
String.prototype.myReverse=function(){ for(var i=this.length-1;i>=0;i--){ console.log(this[i]); } }; var str = "abcdefg"; str.myReverse();
5.原型及原型链
function Person(name, age){ this.name = name; this.age = age; } //通过原型来添加要领 Person.prototype.eat = function() { console.log("eat..."); }; var per1 = new Person("zs1", 10); var per2 = new Person("zs2", 20); console.log(per1.eat == per2.eat); // true console.log(per1.__proto__ == Person.prototype); // true
* 原型链: 是一种关系,实例东西和原型东西之间的关系,这个关系是通过原型(__proto__)来联系的
* 实例东西与原型东西是通过原型__proto__联系的,这个联系就是原型链
* 原型链最终的指向是Object的prototype中的__proto__是null
6.原型指向可以转变
代码1
function Student() {}; Student.prototype.study = function(){ console.log("我爱学习"); }; //Student的原型指向转变了,原型中本来的study()要领没有了 Student.prototype = { eat: function(){ console.log("我要用饭"); } }; var stu = new Student(); console.dir(stu); stu.eat();//我要用饭 //stu.study();//TypeError: stu.study is not a function
代码2
function Person() {}; Person.prototype.eat = function(){ console.log("我爱用饭"); }; function Student() {}; Student.prototype.study = function(){ console.log("我爱学习"); }; //Student的原型指向转变了,指向了一个实例东西,原型中本来的study()要领没有了 Student.prototype = new Person(); var stu = new Student(); console.dir(stu);
功效一:Student.prototype = new Person();注释失后
{} __proto__: {…} constructor: function Student() study: function study() __proto__: Object { … }
功效二:Student.prototype=new Person();没有注释
{} __proto__: {} __proto__: {…} constructor: function Person() eat: function eat() __proto__: Object { … }
7.原型指向转变如何添加原型要领
温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/web/31440.html
- 上一篇:Web视频合成器Seriously.js入门教程
- 下一篇:很多网站开始贪图便宜