js面向对象-组合使用构造函数模式和原型模式(使用最广泛、认同度最高)
生活随笔
收集整理的這篇文章主要介紹了
js面向对象-组合使用构造函数模式和原型模式(使用最广泛、认同度最高)
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
組合使用構(gòu)造函數(shù)模式和原型模式
構(gòu)造函數(shù)模式用于定義實(shí)例屬性
原型模式用于定義方法和共享的屬性
優(yōu)點(diǎn):每個(gè)實(shí)例都有自己的實(shí)例屬性的副本,但同時(shí)共享對(duì)方法的引用,最大限度的節(jié)省內(nèi)存
function Person(name, age, job) {this.name = name;this.age = age;this.job = job;this.friends = ["Shelby", "Court"]; } Person.prototype = {constructor: Person,sayName: function () {alert(this.name);} }; var person1 = new Person("wwl1", 24, "java"); var person2 = new Person("wwl2", 25, "android"); person1.friends.push("Van"); alert(person1.friends); //"Shelby,Count,Van" alert(person2.friends); //"Shelby,Count" alert(person1.sayName === person2.sayName); //true總結(jié)
以上是生活随笔為你收集整理的js面向对象-组合使用构造函数模式和原型模式(使用最广泛、认同度最高)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: window.open()新开浏览器窗口
- 下一篇: 【前端面试】数据类型与类型检测