将一个指定的对象的原型设置为另一个对象或者null
(既对象的[[Prototype]]
内部属性).
示例:
<script type="text/javascript"> var Car=function(){ this.name="车"; } var benz=new Car(); console.log(benz.name); Object.setPrototypeOf(benz,{name:"小轿车",price:"23456"}); console.log(benz.name); //未重写 console.log(benz.price); </script>
Object.defineProperty
Object.defineProperty(被扩展的对象名,属性名,{属性的值}) 可以用于扩展对象的属性
不过可以指定只读属性
示例:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Object.defineProperty()</title> </head> <body> <script> var tom = { name: "tom" }; tom.age = 90; tom["age"] = 88; console.log("tom.age=" + tom.age); var rose = { name: "rose" }; Object.defineProperty(rose, "age", { value: 98, writable:false //只读 }); rose.age=18; //修改无效 console.log("rose.age=" + rose.age); </script> </body> </html>