2013-02-25 31 views
7

Herkes neden farklı benlik değerleri aldığımı açıklayabilir mi? Kendinin buna referans olduğu yer.Javascript: Kendini ve Bu

function Parent(){ 
    var self = this; 
    this.func = function(){ 
     // self.a is undefined 
     // this.a is 'Test' 
     console.log(self.a, this.a); 
    } 
} 

function Child(x){ 
    this.a = x; 
} 

Child.prototype.__proto__ = new Parent; 
var ch = new Child('Test'); 
ch.func(); 

Kendimi projede kullanıyorum ve bu konuyu ilk defa geçiriyorum.

+0

öz ve bu aynı nesneye atıfta artık. Aşağıdaki link yararlı olabilir: http://stackoverflow.com/questions/962033/what-underlies-this-javascript-idiom-var-self-this –

+0

j javascript çağrı içeriğinin sevinci! – benzonico

+0

'Func''de' Parent'' için 'self' puanları gibi görünüyor, ama '' '' '' '' '' '' '' '' 'işaret eder. – Blender

cevap

9

Bunun nedeni, self'un Parent örneğine başvurmasıdır, ancak yalnızca Child örneğinin a özelliği vardır. Eğer Child örneğinde func çağırdığınızda

function Parent(){ 
    var self = this; // this is an instance of Parent 
    this.func = function(){ 
     console.log(self.a, this.a); 
    } 
} 

function Child(x){ 
    this.a = x; // Instances of Child have an `a` property 
} 

Child.prototype.__proto__ = new Parent; 
var ch = new Child('Test'); 

ch.func(); // Method called in context of instance of Child 

Yani, this o örneğe işaret eder. Bu nedenle this.a, func içinde doğru değeri verir.

1

func, this içinde Child'un bir örneğini ifade eder.

Child.prototype.__proto__ = new Parent; 

Child prototipi Parent örneğine ayarlanır. ch.func() çağrıldığında Yani, func()Child prototip zincirinde, ama yine de bir öznitelik a

yok Parent örneğine bahsediyor Child

self bir örneğidir ch bağlamında çağrılır

daha fazla açıklamak gerekirse:

var p = new Parent(); 

// this.a is undefined because this is an instance of Parent 
p.func(); // undefined undefined 
İlgili konular