javascript创建对象

来源:互联网 发布:mac mysql my.cnf 配置 编辑:程序博客网 时间:2024/06/18 10:23

组合使用构造函数模式和原型模式

function Person(name, age) {    this.name = name,    this.age = age,    this.friends = ["hanmei", "lileilei"]}Person.prototype = {    constructor: Person,    sayName: function () {        alert("hello world")    }}var p = new Person;var t = new Person;p.friends.push("DIdi")console.log(p.friends)// ["hanmei", "lileilei", "DIdi"]console.log(t.friends)// ["hanmei", "lileilei"]

实例属性在构造函数中定义,而实例共享的属性constructor和方法则是在原型中定义的。
构造函数与原型混成的模式,是定义引用类型的一种默认模式