如何从方法JS访问类变量

问题描述 投票:4回答:2

我是javascript的新手,我正试图用一些方法创建一个简单的类,但我有一个问题,我无法弄清楚我做得不好。

var SpotifyWebApi = require('spotify-web-api-node');

const my_client_id = "xxx";
const my_secret = "xxx";

class Spotify {
    constructor() {
         this.spotifyApi = new SpotifyWebApi({
            redirectUri: 'http://localhost:8081/spotifyCallback',
            clientId: my_client_id,
            clientSecret: my_secret
        }); 
    }

    connect() {
        console.log(this.spotifyApi.redirectUri);
        return spotifyApi.createAuthorizeURL('teststate', ['user-read-private', 'user-read-email']);
    };
}

在这里,当我尝试登录到控制台spotifyApi.redirectUri时,我得到了undefined(尝试使用和不使用this关键字)。

javascript node.js asynchronous spotify
2个回答
2
投票

您访问对象的方式不正确。看下面的代码和输出。

const SpotifyWebApi = require('spotify-web-api-node');
const my_client_id = "xxx";
const my_secret = 'xxx';
const redirectUri='http://localhost:8081/spotifyCallback';

    class Spotify {       
        constructor(my_client_id, my_secret, redirectUri) {
            this.spotifyApi = new SpotifyWebApi({
                clientId: my_client_id,
                clientSecret: my_secret,
                redirectUri: redirectUri
            });
        }        
        connect() {
            console.log(JSON.stringify(spotify.spotifyApi._credentials,null,4));
            console.log(this.spotifyApi._credentials.redirectUri);       
            return this.spotifyApi.createAuthorizeURL(['user-read-private', 'user-read-email'],'teststate');
        };
    }

    //Instantiate
    const spotify = new Spotify(my_client_id, my_secret ,redirectUri);
    const connectObject = spotify.connect();

输出:

    {
    "clientId": "xxx",
    "clientSecret": "xxx",
    "redirectUri": "http://localhost:8081/spotifyCallback"
    }
    http://localhost:8081/spotifyCallback

你还没有传递createAuthorizeURL的正确参数。看看signautre abouve和spotify-web-api-node


3
投票

这是因为你的lib(https://github.com/thelinmichael/spotify-web-api-node)在实例化时使用redirectUri作为选项,但不将它作为属性公开。

如果您仍然需要它,请将redirectUri放在类属性中,如下所示:

const SpotifyWebApi = require('spotify-web-api-node');

class Spotify {
    constructor(my_client_id, my_secret) {
         this.redirectUri = 'http://localhost:8081/spotifyCallback';
         this.spotifyApi = new SpotifyWebApi({
            redirectUri: this.redirectUri,
            clientId: my_client_id,
            clientSecret: my_secret
        }); 
    }

    connect() {
        console.log(this.redirectUri);
        return this.spotifyApi.createAuthorizeURL('teststate', ['user-read-private', 'user-read-email']);
    };
}

const my_client_id = "xxx";
const my_secret = "xxx";

// Now you can instantiate your class with this :
const spotify = new Spotify(my_client_id, my_secret);
const yourToken = spotify.connect();

我用一些好的做法编辑了我的答案(添加构造函数参数,使用this,...)

© www.soinside.com 2019 - 2024. All rights reserved.