“this” inside object [duplicate]

末鹿安然 提交于 2019-11-27 11:01:38
// Your code
var wF = {
       w : 560,
       h : (312 - 42) / (560 / this.w) + 42
};

this isn't what you think it is

Javascript has no block scope, only function scope: this inside the definition for wF does not refer to wF.

(And so this.w, whatever this is, is likely undefined. Dividing by undefined yields NaN.)

So then you might try:

// Let's not use `this`
var wF = {
       w : 560,
       h : (312 - 42) / (560 / wF.w) + 42
};

You haven't finished defining the object yet

However, you're still defining the object where you attempt to use wF.w: it's not ready for that yet.


Solution

So, yes, you will have to use two variables... or set up the object in stages:

// We can't even use `wF`; split up the property definitions
var wF = {};
wF.w = 560;
wF.h = (312 - 42) / (560 / wF.w) + 42;

Hi just redefine your second property as a function object and it will work. I think it is possible to access the context of the calling object from within a function

var wF = {
    w : 560,
    h : function() { return (312 - 42) / (560 / this.w) + 42; }
};

alert(wF.h())
Paul Perigny

The this keyword refers to the calling context, not an object.

You need to do this in two steps like so:

var wF = { w: 560 };
wF.h = (312 - 42) / (560 / wF.w) + 42;

You don't need to wrap the {...} in an Object(). It is already an object literal.

this doesn't operate inside the object literal, it will point to the object that the function is currently running in so:

function fn() {
   var wF = { w : 560, h : (312 - 42) / (560 / this.w) + 42 };
}

fn();

will cause this to point to the window object.

EDIT: Previous code was not intended to be an answer, just a demonstration of what this is. Another possiblity would be to use a function that takes the width as an argument:

function getObject(width) {
    width = width || 560; //Default value to 560
    return { w: width, h : (312 - 42) / (560 / width) + 42 };
}

var wF = getObject(); //To get the default value, or specify a width otherwise.

When you use this in a JSON object declaration, it points to the current instance.

You can try this code in your console to understand it better:

Object({ w : 560, h : (312 - 42) / (560 / function(e){console.log(e);return e.w;}(this)) + 42 });
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!