javascript - 在原型(prototype)中无法访问此内容

标签 javascript

为什么 this 在下面的代码中提示为 undefined

http://jsfiddle.net/7kwXd/6/

var testObj = {};

testObj.aMethod = function() {
    this.testVar = "thing"
    alert(this.anObject.dimension1);
    alert(this.anObject.dimension2);
};

testObj.aMethod.prototype.anObject = {
   dimension1 : this.testVar,
   dimension2 : "thing2"
};

var testing = new testObj.aMethod();

最佳答案

您正在创建一个没有任何对象上下文的对象 ({dimension1: this.testVar, dimension2: "thing2"})。 this 当时应该是什么?之后,您将其分配给 testObj.aMethod.prototype.anObject

您可以使用这样的代码来实现您想要的:

var testObj = {};

testObj.aMethod = function() {
    this.testVar = "thing"
    alert(this.anObject.dimension1);
    alert(this.anObject.dimension2);
};

testObj.aMethod.prototype.getAnObject = function() {
   return {
       dimension1 : this.testVar,
       dimension2 : "thing2"
   };
};

var testing = new testObj.aMethod();

然后使用 testing.getAnObject().dimension1 访问该对象。

关于javascript - 在原型(prototype)中无法访问此内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19740910/

相关文章:

javascript - css 按钮样式无法使用带有 vue.js 的 <style> 标签

javascript - 如何在 javascript 中返回消息 "Please enter a valid number"

javascript - 如何将 map 运算符用作mergeMap?

javascript - 想要从字符串中删除花括号

javascript - 使用 vue.js 和 bootstrap 4 的弹出窗口

javascript - 将 ember-js 升级到 1.12.0 并将 ember-cli 升级到 0 0.2.5 时的缺陷

javascript - 使用 jquery 按钮重置 tr 输入字段

javascript - jPlayer seekable 在 IE 中不工作

javascript - 增加字段上的日期

javascript - 基于状态响应条件渲染