function Person(){
}
複製代碼
var person1 = new Person()
var person2 = new Person()
複製代碼
console.log(person1 instanceof Person) //true
console.log(person2 instanceof Person) //true
複製代碼
console.log(person1.constructor === Person) //true
console.log(person2.constructor === Person) //true
複製代碼
function Person(name){
this.name = name;
this.sayName = function(){
console.log(this.name)
}
}
var person1 = new Person('aaa')
var person2 = new Person('bbb')
console.log(person1.name) //aaa
console.log(person2.name) //bbb
person1.sayName() //aaa
person2.sayName() //bbb
複製代碼
var book = {
title:'111'
}
console.log(title in book) //true
console.log(book.hasOwnPrototype('title')) //true
複製代碼
雖然book中沒有定義hasOwnPrototype(),可是可使用,由於該方法存在Object.prototype中。數組
鑑別一個屬性是不是原型屬性函數
function hasPro(object,name){
return name in object && object.hasOwnPrototype(name)
}
//true 表明是原型屬性
//false 表明不是原型屬性
複製代碼
var object = {}
console.log(Object.prototype.isPrototypeOf(object)) //true
複製代碼
function Person(name){
this.name = name;
}
Person.prototype.sayName = function(){
console.log(this.name)
}
var p1 = new Person('aaa')
var p2 = new Person('bbb')
console.log(p1.name) //aaa
console.log(p2.name) //bbb
p1.sayName() //aaa
p2.sayName() //bbb
複製代碼
上面把sayName()方法放在了Person的原型對象裏面,因此用new建立出來的對象實例能夠共用。p1和p2對象均可以使用sayName()方法。this值分別被賦值在p1和p2中。ui
若是在原型對象上添加引用類型的值時,會形成多個對象同時改變。this
function Person(name){
this.name = name;
}
Person.prototype.sayName = function (){
console.log(this.name)
}
Person.prototype.favorite = [] //數組,引用類型
var p1 = new Person('aaa')
var p2 = new Person('bbb')
p1.favorite.push('ccc')
p2.favorite.push('ddd')
console.log(p1.favorite) //['ccc','ddd']
console.log(p2.favorite) //['ccc','ddd']
// 由於在原型對象上添加了引用類型,致使p1和p2對象都添加了ccc和ddd
複製代碼
function Person(name){
this.name = name
}
Person.prototype = {
sayName:function(){
console.log(this.name)
},
toString:function(){
return this.name
}
}
複製代碼
var p1 = new Person('aaa')
console.log(p1 instanceof Person) //true
console.log(p1.constructor === Person) //false
console.log(p1.constructor === Object) //true
// 能夠看出來對象實例p1的constructor指向了Objcet
複製代碼
function Person(name){
this.name = name
}
Person.prototype = {
constructor:Person,
sayName:function(){
console.log(this.name)
}
}
var p1 = new Person('aaa')
console.log(p1 instanceof Person) //true
console.log(p1.constructor === Person) //true
console.log(p1.constructor === Object) //false
複製代碼
Array.prototype.sum = function(){
return this.reduce((pre,cur)=>{
return pre + cur
})
}
var num = [1,2,3]
var res = num.sum()
console.log(6)
複製代碼