7

谁能解释为什么我会得到不同的自我价值和这个?self 是对此的引用。

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();

我一直在项目中使用自我,这是我第一次遇到这个问题。

4

4 回答 4

9

这是因为self引用 的实例Parent,但只有 的实例Child具有a属性。

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

因此,当您调用func的实例时Childthis指的是该实例。这就是为什么this.a在里面给你正确的值func

于 2013-02-25T09:34:06.610 回答
1

在 内functhis指的是 的一个实例Child

Child.prototype.__proto__ = new Parent;

的原型Child设置为 的实例Parent。所以当ch.func()被调用时,func()是在 的原型链上Child,但是在其上下文中被调用的ch是 的实例Child

self仍然是指Parent没有属性的实例a

进一步说明:

var p = new Parent();

// this.a is undefined because this is an instance of Parent
p.func(); // undefined undefined
于 2013-02-25T09:43:28.700 回答
0

var myObject = {
    foo: "bar",
    func: function() {
        var self = this;
        console.log("outer func1:  this.foo = " + this.foo); //bar
        console.log("outer func2:  self.foo = " + self.foo); //bar
        (function() {
            console.log("inner func3:  this.foo = " + this.foo); //undefind
            console.log("inner func4:  self.foo = " + self.foo);//bar
        }());
    }
};
myObject.func();

于 2018-09-13T01:46:49.170 回答
0

function Foo() {
  this.bar = 'bar';
  return this;
}
Foo.prototype.test = function(){return 1;}



function Bar() {
  this.bro = 'bro';
  return this;
}
Bar.prototype.test2 = function(){return 2;}

function Cool2() {
  Foo.call(this);
  Bar.call(this);

  return this;
}
//console.log(Object.create(Bar.prototype));
var combine = Object.create(Foo.prototype);
//console.log(combine);

$.extend(combine, Object.create(Bar.prototype));
$.extend(combine, Object.create(Foo.prototype));

Cool2.prototype = Object.create(combine);
//Cool2.prototype.constructor = Cool2;

var cool = new Cool2();
 

console.log(cool.test()); // 1
console.log(cool.test2()); //2
console.log(cool.brow) //bro
console.log(cool.bar) //bar
console.log(cool instanceof Foo); //true
console.log(cool instanceof Bar); //false


 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>

于 2018-09-13T02:22:51.523 回答