众所周知,我们可以使用Object.defineProperty()定义对象的某些属性,但是当我运行以下代码时,它将引发错误!我认为Dom对象和js Object {}之间可能会有一些区别。如果有人可以帮助我,我将不胜感激!
var inn = document.getElementById("search_form_input");//a input element
inn.nodeType;// 1 elementNode
inn.value;//output the value
typeOf(inn);//object
// inn is an Object , so I try the below function
Object.defineProperties(inn,'value',{
set:function(){
return console.log("setting inn value")
}
})
这会产生以下错误:
VM710:1 Uncaught TypeError: Property description must be an object: v
at Function.defineProperties (<anonymous>)
at <anonymous>:1:8
答案 0 :(得分:2)
您正在混合Object.defineProperties和Object.defineProperty。
检查两个功能文档:
Object.defineProperty(obj,prop,描述符)
Object.defineProperties(obj,props)
假设您想使用Object.defineProperty
,那么如果使用正确的函数,代码就可以工作:
var inn = document.getElementById("search_form_input");//a input element
inn.nodeType;// 1 elementNode
inn.value;//output the value
console.log(typeof inn);//object
// inn is an Object , so I try the below function
Object.defineProperty(inn,'value',{
set:function(){
return console.log("setting inn value")
}
});
inn.value = "test";
<input type="text" id="search_form_input"/>
答案 1 :(得分:1)
Object.defineProperties(obj, props)
有2个参数,第二个是对象。您正在传递一个字符串作为第二个参数。