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)
复制代码