构造函数用来初始化新创建的对象。
构造函数自动拥有prototype属性。
构造函数的prototype属性被用作新对象的原型。
prototype属性指向一个对象,该对象为新对象的原型对象。
原型对象保存构造函数的方法,原型对象中有唯一一个不可枚举属性constructor。constructor指向构造函数。
function f(x){this.x=x;} f.prototype.square=function(){ return this.x*this.x; } console.log(f.prototype.constructor===f);//true
构造函数f扩充方法:f.prototype.函数名=function(){}。
f初始化的新对象继承f的属性和prototype中的方法。也可以自定义私有属性和方法。var a=new f(); a.x=2; a.y=3;//a的私有属性 a.sub=function(){//a的私有方法 return this.x-this.y;//this指向a } console.log(a.square());//4 console.log(a.sub());//-1 console.log(a.hasownproperty("sub"));//true。hasownproperty检测方法是否为私有的方法。 console.log(a.hasownproperty("square"));//false console.log(a.constructor===f);//true。继承的constructor以上为个人的一些理解,希望能帮助到部分人,也欢迎矫正、补充。
由于本人资质尚浅,望大神们勿喷。
如对本文有疑问, 点击进行留言回复!!
javascript从入门到跑路-----小文的js学习笔记(19)------- js的垃圾回收机制
Agora 开源 | 一个 Demo,帮你快速实现社交直播四大场景
网友评论