“ .this”未修改原始对象

时间:2019-06-18 18:38:39

标签: javascript

我正在使用javascript数据结构进行一些练习,并且实质上是在尝试扩展Array。

class Collection {
    constructor(array){
        let collection = Object.create(Array.prototype);

        collection = (Array.apply(collection, array) || collection);

        collection.clear = () => {
            while(this.length > 0){
                this.pop();
            }

            return this
        };

        return(collection);
    }; }

问题是当我执行以下操作

c = new Collection([1,2,3]);
c.clear();
我期望c时,

[1,2,3]仍然是[ ]。为什么修改this不修改c

2 个答案:

答案 0 :(得分:2)

  

为什么修改此内容不会修改c?

因为import bs4 import requests for page_number in range(1, 411): print("-" * 35, page_number, "-" * 35) resp = requests.get("https://www.pealim.com/dict/?page={}".format(page_number)) soup = bs4.BeautifulSoup(resp.text, "html.parser") table_elem = soup.find("tbody") rows = table_elem.find_all("tr") for row in rows: hebrew = row.find("span", class_="menukad").get_text() latin = row.find("span", class_="dict-transcription").get_text() print("{}: {}".format(hebrew, latin)) 引用了您用this创建的Collection的实例,而构造函数返回了new Collection(...)的值;在这种情况下不是let collection

此外,您的代码十分有趣。我认为这就是您要构建的:

this

答案 1 :(得分:0)

这是定义函数的方式。 当您重新定义为lamda表达式时,此值未正确绑定。 更改为普通函数声明。

class Collection {
    constructor(array){
        let collection = Object.create(Array.prototype);

        collection = (Array.apply(collection, array) || collection);
debugger;
        collection.clear = function()  {
            while(this.length > 0){
                this.pop();
            }

            return this
        };

        return(collection);
    }; }

var c = new Collection([1,2,3]);
c.clear();
console.log(c);

相关问题