| 案例 |
function Person(name) { this.name = name this.friends = [‘Shelby‘, ‘Court‘] } Person.prototype.sayName = function() { console.log(this.name) } var person1 = new Person() var person2 = new Person() person1.friends.push(‘Van‘) console.log(person1.friends) //["Shelby", "Court", "Van"] console.log(person2.friends) // ["Shelby", "Court"] console.log(person1.friends === person2.friends) //false |
function Person(name, job) { var o = new Object() o.name = name o.job = job o.sayName = function() { console.log(this.name) } return o } var person1 = new Person(‘Jiang‘, ‘student‘) person1.sayName() |
function Person(name, job) { // 屬性 this.name = name this.job = job // 方法 if(typeof this.sayName !== ‘function‘) { Person.prototype.sayName = function() { console.log(this.name) } } } var person1 = new Person(‘Jiang‘, ‘Student‘) person1.sayName() |
function Person(name, job) { var o = new Object() o.name = name o.job = job o.sayName = function() { console.log(name) } return o } var person1 = Person(‘Jiang‘, ‘student‘) person1.sayName() |