当前位置: 移动技术网 > IT编程>开发语言>JavaScript > javascript中构造函数和prototype属性

javascript中构造函数和prototype属性

2019年06月09日  | 移动技术网IT编程  | 我要评论

构造函数用来初始化新创建的对象。

构造函数自动拥有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
以上为个人的一些理解,希望能帮助到部分人,也欢迎矫正、补充。

由于本人资质尚浅,望大神们勿喷。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网