javascript-prototype
3594 ワード
1、 prototype , , , 。
2、 , ,js 。
, , , javascript , 。
:Object.prototype.[methodfield] ;
3、isPrototypeOf( )
4、ECMA5:Object.getPrototypeOf():
5、object.hasOwnProperty(attribute)
6、in ( )
7、ECMA5 Object.keys(); keys ECMA5 Object.getOwnPropertyNames :
function Person(name,age){
this.name=name
this.age=age
}
//
var obj=Person.prototype
console.log(obj.constructor)
obj.eating=function(){
console.log('eating...')
}
obj.singing=function () {
console.log('singing...')
}
var p1=new Person('z3',23)
var p2=new Person('li4',20)
p1.eating()
p2.singing()
//Object.getPrototypeOf( )
console.log(Object.getPrototypeOf(p1)==Person.prototype)
#
function Person(){}
Person.prototype={
constructor:Person,
name:'z3',
age:20,
eating:function(){console.log('eating...')}
}
// 1: 、 2: 、 3:Option
Object.defineProperty(Person.prototype,'constructor',{
enumerable:false,
value:Person
})
var p1=new Person()
console.log(Person.prototype.constructor)
// keys
for(i in p1){
console.log(i)
}
#
// :
function Person(name,age){
this.name=name
this.age=age
}
Person.prototype={
constructor:Person,
sayName:function(){console.log('my name is :'+this.name+"; i am "+this.age)}
}
var p1=new Person('li4',20)
var p2=new Person('w5' ,24)
p1.sayName()
p2.sayName()
# : 、
// 、 、
//1、 .prototype =
//2、 .constructor = ( )
//3、 .isPrototypeOf( )
//4、 .isInstannceOf( )
//
function Father(name){
this.name=name
}
//
Father.prototype={
constructor:Father,
say:function(){
console.log('i am '+this.name)
}
}
//
function Child(name){
this.name=name
}
// ( js )
Child.prototype=new Father()
var c1=new Child('child')
//1、
console.log(Father.prototype.isPrototypeOf(c1))
//2、
console.log(c1.constructor)
// js
console.log(c1.name)
c1.say()
# : , ( )
//
function Father(name){
// this.name=name
this.name=name
}
//
Father.prototype={
constructor:Father,
say:function(){
console.log('i am '+this.name)
}
}
//
function Child(name,age){
//call apply
Father.call(this,name)
this.age=age
}
var c1=new Child('li4',21)
console.log(c1.name)
console.log(c1.age)
c1.say() // ,
# : ,
// : , ( )
//
function Child(name,age){
//call apply
Father.call(this,name)
this.age=age
}
// : ;
Child.prototype=new Father()
var c1=new Child('li4',21)
console.log(c1.name)
console.log(c1.age)
c1.say()