繁体   English   中英

为什么我不能从Object实例访问Object方法?

[英]Why I can't access Object methods from Object instance?

对象构造函数有很多方法,例如Object.assign()和Object.create(),但是为什么我不能从Object实例访问这些方法?

var test  = new Object();
//this will return error
test.create();

这是因为createassign和许多其他方法都是静态方法。 静态方法属于该类,因此您不能从该类的实例调用它们。 在这里您可以找到有关js中静态方法的更多信息

class Tripple {
  static tripple(n) {
    n = n | 1;
    return n * 3;
  }
}

class BiggerTripple extends Tripple {
  static tripple(n) {
    return super.tripple(n) * super.tripple(n);
  }
}

console.log(Tripple.tripple());
console.log(Tripple.tripple(6));
console.log(BiggerTripple.tripple(3));
var tp = new Tripple();
console.log(tp.tripple()); //Logs 'tp.tripple is not a function'

您已经用新变量创建了一个对象。 您可以尝试使用create关键字来创建新对象

var testObj = Object.create(null);

typeof(testObj) // Object
console.log(testObj) // Object with prototype object as null

// Set property to object
testObj.name = "Stackoverflow";

console.log(testObj)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM