简体   繁体   English

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

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

There are many methods for Object constructor, like Object.assign() and Object.create(), but why I can't access these methods from Object instances? 对象构造函数有很多方法,例如Object.assign()和Object.create(),但是为什么我不能从Object实例访问这些方法?

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

That is because create , assign and many others are static methods. 这是因为createassign和许多其他方法都是静态方法。 Static methods belongs to the class so you cannot call them from an instance of that class. 静态方法属于该类,因此您不能从该类的实例调用它们。 Here you can find more info about static methods in js 在这里您可以找到有关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'

You already created a object with new variable. 您已经用新变量创建了一个对象。 You can try this to create new object using create keyword 您可以尝试使用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