本篇内容主要讲解“js使用构造函数有哪些缺点”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“js使用构造函数有哪些缺点”吧!
1、不是原型链继承,只是借用构造函数,所以不能继承原型的属性和方法。
2、虽然构造函数中定义的属性和方法是可以访问的,但是每个实例都被复制了。
如果例子太多,方法太多,占用内存很大,那么方法就在构造函数中定义,函数的复用就无从谈起。
实例
// 父构造函数
function Father() {
this.name = 'father'
this.speakName1 = function () {
console.log('speakName1')
}
this.speakName2 = function () {
console.log('speakName2')
}
this.speakName3 = function () {
console.log('speakName3')
}
this.speakName4 = function () {
console.log('speakName4')
}
}
// 父原型上 方法
Father.prototype.alertName = function () {
console.log(this.name)
}
// 父原型上 属性
Father.prototype.age = 21
// 子构造函数
function Children() {
Father.call(this)
}
// 创建子实例
let c1 = new Children()
// 调用原型方法,实例访问不到
c1.alertName()
// TypeError: c1.alertName is not a function
// 访问原型属性,实例中未定义
console.log(c1.age)
// undefined
// 可以访问实例属性,但是每个实例都存有自己一份 name 值
console.log(c1.name)
// father
// 可以访问实例方法,但是每个实例都存有自己一份 speakName1() 方法,
// 且方法过多,内存占用量大,这就不叫复用了
c1.speakName1()// speakName1
c1.speakName2()// speakName2
c1.speakName3()// speakName3
c1.speakName4()// speakName4
// instanceof isPrototypeOf 无法判断实例和类型的关系
console.log(Father.prototype.isPrototypeOf(c1))// false
console.log(c1 instanceof Father)// false
到此,相信大家对“js使用构造函数有哪些缺点”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。
原文链接:https://my.oschina.net/u/4246997/blog/4463766