我试图使用fullname
设置对象person
的{{1}}属性,但在注销全名时未定义。
this
这很奇怪,因为在函数内部使用var person = {
name:'yask',
fullname: this.name + ' Srivastava'
}
console.log(person.fullname);
时会引用该对象。在这里它看起来像是被引用到全局对象。(窗口可能......?)
答案 0 :(得分:1)
您可以使用getter,
来完成此操作package receiverhost;
import java.io.*;
import java.net.*;
public class ReceiverHost {
public static void main(String[] args) throws Exception {
//set up socket on port 5000
ServerSocket Server = new ServerSocket(5000);
//set up "cookie"/ text file to be written to/ read from eventually
Writer DB = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("CQ.txt"), "utf-8"));
System.out.println("TCPServer Waiting for client on port 5000");
while(true){
//declare string fromclient
String fromclient;
Socket connected = Server.accept();
System.out.println(" The client" + " " + connected.getInetAddress() + ":" + connected.getPort() + " is connected ");
//read/ retrieve client output stream
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connected.getInputStream()));
fromclient = inFromClient.readLine();
if(fromclient.equals("Q1C")){
//write to CQ.txt
DB.write("Q1: correct");
}
if(fromclient.equals("Q2C")){
//write to CQ.txt
DB.write("Q2: correct");
}
}
}
}
基本上,你的案例中的var person = {
name:'yask',
get fullname(){ return this.name + ' Srivastava' }
}
console.log(person.fullname);
会将词汇范围的上下文指向对象的功能,而不是对象本身。