-1

因此,当我们创建用于创建新对象的构造函数时,new 关键字会做 3 件事,我将对其进行解释,但如果我错了请纠正我,我想确保我是正确的

首先我将创建一个构造函数

function ObjectCreate(){
    this.a = "a";
    this.b = "b";

    ObjectCreate.prototype.show = function(){
        alert(this.a+" "+this.b);
    }
}

obj1 = new ObjectCreate();

现在 new 关键字做的第一件事是创建新对象并将其秘密链接设置为其构造函数的原型并将其传递给构造函数,现在this可以引用它,请注意this此时不引用 obj1,因为一旦构造函数完成创建object 只有这样,它才会将新创建的对象返回给 obj1 变量。我问这个问题是因为有人说this在这种情况下指的是 obj1 对象。所以我就在这里。

4

3 回答 3

2

你的措辞有点混乱,但我会尽力而为。首先,你应该注意到你的花括号有点偏离。您的代码应如下所示:

function ObjectCreate(){
   this.a = "a";
   this.b = "b";
}

ObjectCreate.prototype.show = function(){
     alert(this.a+" "+this.b);
}

obj1 = new ObjectCreate();

你需要定义你的构造函数,然后将东西附加到它的原型上。

当您调用构造函数时,this关键字基本上指正在创建的新对象。这很重要,因为例如,您可以编写如下构造函数:

function ObjectCreate(x,y){
   this.a = x*x;
   this.b = y*x+4;
}
obj1 = new ObjectCreate(10,20);

与所有构造函数一样,这里this指的是正在创建的实例(obj1在本例中为 )。

我认为您建议this引用对象的原型,但这会生成this.a静态this.b变量,这在像这里这样的构造函数中是无用的,因为每次初始化一个新对象时,您都会更改所有先前存在的this.a和的值this.b对象,这只是没有用。

我希望这回答了你的问题。如果没有,请继续并留下评论以进一步澄清。

于 2013-09-27T16:49:07.847 回答
0

在此示例中,在构造函数调用期间,obj1未定义。函数返回后将值分配给obj1变量。ObjectCreate

你可以自己检查一下:

function ObjectCreate(){
    this.a = "a";
    this.b = "b";

    alert(obj1); // yields "undefined"
    ObjectCreate.prototype.show = function(){
        alert(this.a+" "+this.b);
    }
}

var obj1 = new ObjectCreate(); // note "var"
于 2013-09-27T16:56:23.300 回答
0

this似乎没有人提到invoking object.

window.sayHi=function(){
  console.log(this.name);
}
window.name="Window"
window.sayHi();//=Window

var obj={
  name:"obj"
}
obj.fn=window.sayHi;

obj.fn();//=obj

上面的代码表明,当在this上下文中传递函数时会发生变化。如果你不想这样,那么你可以传递一个闭包而不是函数或使用callapplybind

//closure example
obj.fn=(function(w){//w is available because the returned function is a closure
  return function(){
    w.sayHi();
  }
}(window));

obj.fn();//=Window
//using call
obj.fn.call(window);//=Window
//using apply
obj.fn.apply(window);//=Window
//using bind
var boundFn=obj.fn.bind(window);
boundFn();//=Window

那是当您将函数作为参数传递给另一个对象时。当您使用构造函数时this,函数体内将引用要创建的对象。

但是当你传递它的功能时,它可能不是:

var obj={
  name:"obj"
}
var Test=function(){
  this.name="Test";
}
Test.prototype.sayHi=function(){
  console.log(this.name);
};

var t=new Test();
obj.fn=t.sayHi
t.sayHi();//=Test
obj.fn();//=obj

这是大多数人在将对象实例函数传递给 setTimeout 或事件处理程序时陷入的陷阱:

someButton.onclick=t.sayHi;//when button is clicked this will be the button clicked
setTimeout(t.sayHi,100);//when sayHi is executed 'this' will be window

回答关于构造函数体内存在的 obj1 的问题;我会说不(至少不在 Firefox 中)。我没有规范的链接,但 obj1 将this在构造函数返回时设置为:

//clean up window.t
delete window.t;
var Test=function(){
  this.name="Test";
  console.log("and window.t is:",window.t);//undefined
}
Test.prototype.sayHi=function(){
  console.log(this.name);
};

window.t=new Test();

更多关于构造函数、原型、继承、覆盖和调用 super的信息

于 2013-09-28T15:16:50.237 回答