javascript原型找不到属性或是方法或是undefined是怎么会事?

在这上面踩了些坑,原来是写法不能混合着写

function Person(name){
    
    
			this.name=name;
			this.sayHi=function(){
    
    
				return this.name;
			}
		}
		//如果像下面这样写实例时就读取不到数据
		Person.prototype.job="jim";
		Person.prototype={
    
    
				sayHello:function(){
    
    
				return '这是原型';
			}
		};
		var p=new Person("jack");
		console.log(p.job);  //这里是获取不到数据jim的
		
		//这是字面量写法
		Person.prototype={
    
    
			job:"jim",
			sayHello:function(){
    
    
				return '这是原型';
			}
		};
		//普通写法
		Person.prototype.job="jim";
		Person.prototype.sayHello=function(){
    
    
				return '这是原型';
		};
	
	//正确写法选上面一种,就可以获取到数据值和方法的数据。
	console.log(p.job)

猜你喜欢

转载自blog.csdn.net/cdcdhj/article/details/110188470