原型语法
function Student(name,id){ this.name = name; this.id = id; } //获取对象的prototype Student.prototype.type = "student"; Student.prototype.message = function(){ console.log(this.name + "," + this.id); }; //生成实例对象 var student1 = new Student("li",111);
直接使用一个对象字面量对原型对象进行赋值
Student.prototype = { type : "student", message : function(){ console.log(this.name + "," + this.id); }};//可以正常调用student1.message();
但是,需要注意有一点,
student1.constructor
的指向已经发生了改变,因为Student的prototype已经被重置了,constructor的指向找不到,student1.constructor
的值就变成了Object了。解决这一问题,很简单,就是在给
Student.prototrpe
的字面量对象赋值时,需要手动的将constructor属性指向正确的构造函数。constructor : Student //该构造函数是Student
在定义构造函数时,使用原型对象时建议根据成员的功能不同,可以分为以下两种进行设置:
①私有成员,一般就是非函数成员,放到构造函数中;
②共享成员,一般就是函数,放到原型对象种;
当重置了prototype时,记得修正constructor的指向
JS 原生构造函数的原型对象
所有函数都有prototype属性对象
JavaScript中的内置构造函数也有prototype原型对象属性:
- Object.prototype
- Function.prototype
- Array.prototype
- String.pprototype
- Number.protoptype
......扩展数组的原型方法
直接给原型对象添加一个对象字面量的值是不行的,内置构造函数有其保护机制(所以如下这种代码不允许的)。
Array.prototype = { getSum = function(){ var sum = 0; for(var i = 0;i < this.length;i++){ sum += this[i]; } return sum; } };console.dir(Array.prototype);
直接使用Array调用prototype给其添加新属性
Array.prototype.getSum = function(){ var sum = 0; for(var i = 0;i < this.length;i++){ sum += this[i]; } return sum;};console.dir(Array.prototype);
实际开发中是不允许更改JS原生内置对象。
原文转载:http://www.shaoqun.com/a/615571.html
米兰网:https://www.ikjzd.com/w/1304.html
moss:https://www.ikjzd.com/w/1653
原型语法functionStudent(name,id){this.name=name;this.id=id;}//获取对象的prototypeStudent.prototype.type="student";Student.prototype.message=function(){console.log(this.name+","+this.id);};/
6pm:https://www.ikjzd.com/w/317
巴克莱银行:https://www.ikjzd.com/w/2775
cares:https://www.ikjzd.com/w/1302
美国二手奢侈品电商RealReal上市,市值达23.9亿美元:https://www.ikjzd.com/home/99512
降低退款率!Wish瑞典路向物流最新解决方案:https://www.ikjzd.com/home/3669
Shopee商品上新规范!:https://www.ikjzd.com/home/107233
No comments:
Post a Comment