JavaScript之new的模擬實現javascript
function Otaku (name , age){ this.name = name this.age = age this.habit = 'Games' } Otaku.prototype.strength = 60 Otaku.prototype.sayYourName = function(){ console.log('I am ' + this.name) } var person = new Otaku('hy' , 18) console.log(person.name) console.log(person.age) console.log(person.habit) console.log(person.strength) person.sayYourName()
由此能夠看出,實例person能夠:java
function objectFactory(){ var obj = new Object() Constructor = [].shift.call(arguments) obj.__proto__ = Constructor.prototype Constructor.apply(obj , arguments) return obj }
function Otaku(name , age){ this.strength = 60 this.age = age return 'handsome boy'; } var person = new Otaku('hy', '18'); console.log(person.name) // undefined console.log(person.habit) // undefined console.log(person.strength) // 60 console.log(person.age) // 18
第二版數組
function objectFactory(){ var obj = {} Constructor = [].shift.call(arguments) obj.__proto__ = Constructor.prototype var ret = Constructor.apply(obj , arguments) return typeof ret === 'object' ? ret : obj }