js常用设计模式
组合使用构造函数模式和原型模式。其中,构造函数模式用于定义实例属性,而原型模式用于定义方法和共享属性。
例子:
<script> function Person(name,age,job){ this.name = name; this.age = age; this.job = job; this.friends = ["jie","fei"]; } // Person.prototype = { // constructor : Person, // sayName : function(){ // alert(this.name); // } // } Person.prototype.sayName = function(){ alert(this.name); } var person1 = new Person("jie",24,"web"); var person2 = new Person("fei",24,"teacher"); person1.friends.push("wang"); alert(person1.friends); alert(person2.friends); alert(person1.friends == person2.friends); alert(person1.sayName == person2.sayName); </script>