我想确保在类外更改对象的属性时引发错误。这是我尝试执行的操作:
class Example {
constructor(index) {
this.index = index;
Object.defineProperty(this, 'index', {
set() {
throw new AssertionError("can't set attribute");
}
});
}
}
class AssertionError extends Error {
constructor(message) {
super();
this.name = "AssertionError";
this.message = message;
}
}
let example = new Example(5);
console.log(example.index); //prints undefined instead of 5
example.index = 10; // I want to throw an AssertionError here
就像我想要的那样抛出错误,但是索引值未定义。我仍然希望能够在类内部更改属性,但是我想防止属性在类外部更改。
答案 0 :(得分:8)
您可以通过调用public class flyYatra {
public void mainTest() throws IOException, InterruptedException, WebDriverException, SocketException {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\Downloads\\Driver\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addArguments("--incognito");
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
capabilities.setCapability(ChromeOptions.CAPABILITY, options);
WebDriver driver = new ChromeDriver(capabilities);
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
重新定义属性。您应该给它吸气剂:
defineProperty
任何给定的属性名称只能使用一次;属性必须是普通属性或具有getter / setter函数的属性。