typeof与instanceof

作者:追风剑情 发布于:2018-11-16 11:28 分类:TypeScript

示例

class A {public age: number}
class B {
	//定义属性name
	private _name: string;
	public get name() {
		return this._name;
	}
	public set name(value: string) {
		this._name = value;
	}
}

function checkInstanceof(value: A | B)
{
	if (value instanceof A) {
		console.log("instanceof A");
	}
	
	if (value instanceof B) {
		console.log("instanceof B");
	}
	
	//遍历对象上的所有属性
	for (let key in value) {
		if (value.hasOwnProperty(key)) {
			console.log("own property: "+key);
		}else{
			console.log("prototype: "+key);
		}
	}
}

function checkTypeof(value: number|string|boolean|symbol)
{
	if (typeof value === "number") {
		console.log("number");
	}
	if (typeof value === "string") {
		console.log("string");
	}
	if (typeof value === "boolean") {
		console.log("boolean");
	}
	if (typeof value === "symbol") {
		console.log("symbol");
	}
}

checkInstanceof(new A())
checkInstanceof(new B())

checkTypeof(5)
checkTypeof("sss")
checkTypeof(true)

console.log("遍历字面量")
let obj = {name: "xxx", age: 12};
for (let key in obj) {
	if (obj.hasOwnProperty(key)) {
		console.log("own property: "+key);
	}else{
		console.log("prototype: "+key);
	}
}

console.log("遍历函数对象")
function fun1()
{
	this.firstName = "a";
}
fun1.prototype.secondName = "b";
let obj1 = new fun1();
for (let key in obj1) {
	if (obj1.hasOwnProperty(key)) {
		console.log("own property: "+key);
	}else{
		console.log("prototype: "+key);
	}
}

运行测试

111.png

标签: TypeScript

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号