在构造函数对象中访问它

时间:2016-12-08 19:53:13

标签: javascript

我正在尝试访问this中的prototype constructor(我认为这就是所谓的内容?)。

SomethingUseful.prototype = {
    constructor: SomethingUseful,
    init: init,
    someFunction: someFunction,
    mouseDownHandler: mouseDownHander.bind(this)
}

this等于window。所以我尝试了bind(SomethingUseful),当我在thismouseDownHandler时,整个函数以纯文本形式登出,因此我无法使用this中的内容,在实际的mouseDownHandler函数中。

this函数中访问SomethingUseful的{​​{1}}的正确方法是什么(再次,我的名字可能错了,如果我这样做了,请更正,或者让我在评论中知道吗?

2 个答案:

答案 0 :(得分:1)

  

而不是这样做:this.mouseDownHandler = mouseDownHander.bind(this);我想在SomethingUseful.prototype = {中添加它。

那是不可能的。在您尝试将函数绑定到实例时,没有可以将函数绑定到的实例。只有在调用构造函数时或之后,才会有一个实例将函数绑定到。

换句话说:你正在尝试在比萨饼送达之前吃掉它。

相关:How to access the correct `this` context inside a callback?

答案 1 :(得分:1)

对于对象定义,this用于声明“实例属性”,这些属性的值可能因实例而异。

通常,对于存储函数(也称为方法)的属性,该函数不会在实例之间发生变化,因此这些属性通常在对象的原型上进行,因此每个实例都不必存储完全相同的每个其他实例的功能。

当设计一个Object以便稍后创建它的实例时,我们声明一个函数,而不是一个对象文字,因为你不能调用一个对象。

// This is known as a "constructor function" because it is
// intended to produce (construct) objects that will then
// be bound to instance variables:
function SomethingUseful(){
  // This is a regular variable that is scoped to the function
  // it will not be accessible to instances later.
  var a = 10;
  
  // Because of the word "this", this becomes an "instance property"
  // that each instance of SomethingUseful will have. Each instance
  // will start out with a default value of 20, but each instance 
  // can change that value and it won't affect any other instance
  this.someProperty = 20;  
}

// Methods are not set up in the constructor (so they do not become
// instance properties) instead, they are set up on the constructor's
// prototype and inherited into each instance. All instances share
// the same one prototype:
SomethingUseful.prototype.someMethod = function(){
  // Even though this method is not stored with each instance, it 
  // can access the current instance by using "this"
  return this.someProperty;
};


// Make instances of SomethingUseful by calling the constructor function
// which returns object instances. Those instances are stored in different
// variables and that's how we keep the instances separate from each other
var obj1 = new SomethingUseful();
var obj2 = new SomethingUseful();

// Now that we have used the constructor function to create the instances,
// we can ask those instances what function was used to create them:
console.log("The object stored in obj1 was constructed with: " + obj1.constructor.name);

//Check obj1:
console.log("obj1.someProperty is: " +  obj1.someProperty);
obj1.someProperty = 50;
console.log("obj1.someProperty changed and is now: " + obj1.someProperty)
console.log("obj1.someMethod returns: "  + obj1.someMethod());

//Check obj2:
console.log("obj2.someProperty is: " +  obj2.someProperty);
console.log("obj2.someMethod returns: "  + obj2.someMethod());

您正在尝试处理JavaScript为您处理的事情。只需在event属性中定义所需的功能,然后继续创建对象的实例。 JavaScript将确保每个实例都能获得您的功能。